ES2016 Class,Sinon Stub构造函数

kly*_*lyd 12 javascript mocha.js babel node.js sinon

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

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

.babelrc文件:

{
  "presets": [
    "es2016"
  ],
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-async-to-generator"
  ]
}
Run Code Online (Sandbox Code Playgroud)

测试:

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

结果:

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)
Run Code Online (Sandbox Code Playgroud)

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

Wen*_*han 12

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

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);
  });
});
Run Code Online (Sandbox Code Playgroud)