ES2016 Class,Sinon Stub构造函数

问题描述 投票:8回答:4

我正试图与sinon和es2016进行超级电话,但我没有太多运气。任何想法为什么这不起作用?

运行节点6.2.2,这可能是其实现类/构造函数的问题。

.babelrc文件:

{
  "presets": [
    "es2016"
  ],
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-async-to-generator"
  ]
}

测试:

import sinon from 'sinon';

class Foo {
  constructor(message) {
    console.log(message)
  }
}

class Bar extends Foo {
  constructor() {
    super('test');
  }
}

describe('Example', () => {
  it('should stub super.constructor call', () => {
    sinon.stub(Foo.prototype, 'constructor');

    new Bar();

    sinon.assert.calledOnce(Foo.prototype.constructor);
  });
});

结果:

test
AssertError: expected constructor to be called once but was called 0 times
    at Object.fail (node_modules\sinon\lib\sinon\assert.js:110:29)
    at failAssertion (node_modules\sinon\lib\sinon\assert.js:69:24)
    at Object.assert.(anonymous function) [as calledOnce] (node_modules\sinon\lib\sinon\assert.js:94:21)
    at Context.it (/test/classtest.spec.js:21:18)

注意:这个问题似乎只发生在构造函数中。我可以窥探从父类继承的方法而没有任何问题。

javascript node.js mocha sinon babel
4个回答
8
投票

由于JavaScript实现继承的方式,您需要setPrototypeOf subClas。

const sinon = require("sinon");

class Foo {
  constructor(message) {
    console.log(message);
  }
}

class Bar extends Foo {
  constructor() {
    super('test');
  }
}

describe('Example', () => {
  it('should stub super.constructor call', () => {
    const stub = sinon.stub().callsFake();
    Object.setPrototypeOf(Bar, stub);

    new Bar();

    sinon.assert.calledOnce(stub);
  });
});

0
投票

你需要spy而不是stub

sinon.spy(Foo.prototype, 'constructor');

describe('Example', () => {
  it('should stub super.constructor call', () => {
    const costructorSpy = sinon.spy(Foo.prototype, 'constructor');
    new Bar();
    expect(costructorSpy.callCount).to.equal(1);
  });
});

*****更新******上面没有按预期工作,我添加了这种方式,现在正在工作。

 describe('Example', () => {
    it('should stub super.constructor call', () => {
      const FooStub = spy(() => sinon.createStubInstance(Foo));
      expect(FooStub).to.have.been.calledWithNew;
    });
 });

0
投票

它对我也不起作用。我管理了一个适合我的解决方法,我也使用间谍:

class FakeSchema {
  constructor(newCar) {
    this.constructorCallTest();
    this.name = newCar.name;
  }

  constructorCallTest() {
    mochaloggger.log('constructor was called');
  }

}

// spy that tracks the contsructor call
var fakeSchemaConstrSpy = sinon.spy(FakeCarSchema.prototype,'constructorCallTest');

希望这很有帮助


0
投票

如果您在浏览器环境中,以下内容也适用:

let constructorSpy = sinon.spy(window, 'ClassName');

例如,这适用于Jasmine。

Mocha反而在Node环境中运行,没有window。你要找的变量是global

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