为什么在es6中需要构造函数?

Pal*_*tro 0 javascript unit-testing ecmascript-6 enzyme

为什么当我在test id中编写'new ServerNotificationApi'时不会调用构造函数,因为我new ServerNotificationApi.constructor()工作,但我无法理解为什么当我写 new ServerNotificationApi单元测试时出现错误'TypeError:_serverNotifications.default不是构造函数'

class ServerNotificationApi {
        constructor() {
            SignalR.initConnection(url.serverNotificationHubName)
        }

        subscribe = callback => SignalR.subscribe(url.entityChanged, url.serverNotificationHubName, callback);

        unsubscribe = callback => SignalR.unsubscribe(url.entityChanged, url.serverNotificationHubName, callback);
    }

    export default new ServerNotificationApi()
Run Code Online (Sandbox Code Playgroud)

测试

 it('constructor should call signalR method \'initConnection\'', () => {
        sinon.stub(SignalR, 'initConnection')

        new ServerNotificationApi.constructor()

    SignalR.initConnection.calledWith(url.serverNotificationHubName).should.be.true

        SignalR.initConnection.restore()
    })
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 6

export default new ServerNotificationApi()
               ???
Run Code Online (Sandbox Code Playgroud)

您正在导出类的实例,而不是类本身.你基本上是这样做的:

let foo = new ServerNotificationApi();
new foo();
Run Code Online (Sandbox Code Playgroud)

哪,是的,不起作用.摆脱newexport.