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

时间:2017-12-20 10:15:06

标签: javascript unit-testing ecmascript-6 enzyme

为什么当我编写新的ServerNotificationApi'在test id中没有调用构造函数,对我来说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()

测试

 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()
    })

1 个答案:

答案 0 :(得分:6)

export default new ServerNotificationApi()
               ↑↑↑

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

let foo = new ServerNotificationApi();
new foo();

哪,是的,不起作用。摆脱new中的export