Javascript 如何验证是否使用sinon调用了构造函数

Javascript 如何验证是否使用sinon调用了构造函数,javascript,unit-testing,typescript,sinon,sinon-chai,Javascript,Unit Testing,Typescript,Sinon,Sinon Chai,我需要断言是否使用sinon调用了构造函数。下面是我如何创建一个间谍 let nodeStub: any; nodeStub = this.createStubInstance("node"); 但是我如何验证这个构造函数是用相关参数调用的呢?下面是构造函数的实际调用方式 node = new node("test",2); 任何帮助都将不胜感激 下面是我的代码 import {Node} from 'node-sdk-js-browser'; export class MessageB

我需要断言是否使用sinon调用了构造函数。下面是我如何创建一个间谍

let nodeStub: any;
nodeStub = this.createStubInstance("node");
但是我如何验证这个构造函数是用相关参数调用的呢?下面是构造函数的实际调用方式

 node = new node("test",2);
任何帮助都将不胜感激

下面是我的代码

import {Node} from 'node-sdk-js-browser';

export class MessageBroker {

    private node: Node;
    constructor(url: string, connectionParams: IConnectionParams) {
        this.node = new Node(url, this.mqttOptions, this.messageReceivedCallBack);
    }
}

给定以下代码myClient.js:

const Foo = require('Foo');

module.exports = {
   doIt: () => {
      const f = new Foo("bar");
      f.doSomething();
  }
}
您可以编写如下测试:

const sandbox = sinon.sandbox.create();
const fooStub = {
   doSomething: sandbox.spy(),
}

const constructorStub = sandbox.stub().returns(fooStub);
const FooInitializer = sandbox.stub({}, 'constructor').callsFake(constructorStub);

// I use proxyquire to mock dependencies. Substitute in whatever you use here.
const client2 = proxyquire('./myClient', {
    'Foo': FooInitializer,
});

client2.doIt();

assert(constructorStub.calledWith("bar"));
assert(fooStub.doSomething.called);     

嘿,伙计,我需要测试的类叫做MessageBroker。它有一个导入行,“从'Node sdk js browser';导入{Node}”。这里的节点是一个命名的导入。它来自模块节点sdk js浏览器。我需要节点构造函数来监视和验证是否调用了它。你能编辑这个例子来适应这个吗?因为我不熟悉Javascript,所以它相当混乱:(它应该会提供您的总体想法。如果您提供代码(甚至是简化的代码)我可以更新我的示例。我已经和我的代码伙伴编辑了这个问题。我正在为MEssageBroker类编写测试。我需要验证在调用MEssageBroker构造函数时是否调用了节点构造函数。如果您能帮我举一个例子,那将非常好:(更新了我的帖子,但使用es5而不是es6编写了它。)
const sandbox = sinon.sandbox.create();
const fooStub = {
   doSomething: sandbox.spy(),
}

const constructorStub = sandbox.stub().returns(fooStub);
const FooInitializer = sandbox.stub({}, 'constructor').callsFake(constructorStub);

// I use proxyquire to mock dependencies. Substitute in whatever you use here.
const client2 = proxyquire('./myClient', {
    'Foo': FooInitializer,
});

client2.doIt();

assert(constructorStub.calledWith("bar"));
assert(fooStub.doSomething.called);