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

问题描述 投票:0回答:1

为什么当我在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()

测试

 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()
    })
javascript unit-testing ecmascript-6 enzyme
1个回答
6
投票
export default new ServerNotificationApi()
               ↑↑↑

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.