【问题标题】:sinon is not mocking import functionsinon 没有模拟导入功能
【发布时间】:2019-07-22 19:15:48
【问题描述】:

我有以下代码。 Sinon 未能模拟 doSomething() 并打印实际字符串而不是 'hello'

//file.js

import { doSomething } from 'my-npm-package';
module.exports = () => doSomething();

这是测试文件:

//file.spec.js

import sinon from 'sinon';
import { expect } from 'chai';
import * as apis from 'my-npm-package';
import someFunction from '../file';

describe('TEST', () => {
  let stub;
  beforeEach(() => {
    stub = sinon.stub(apis, 'doSomething').returns('hello');
  });

  afterEach(() => {
    stub.restore();
  });

  it('test', async () => {
    someFunction();
    expect(stub.calledOnce).to.equal(true);
  });
});

【问题讨论】:

  • 这对我来说按预期工作。这可能是编译的问题,您是在使用webpack 还是在使用babel 做任何不寻常的事情?
  • 当我使用sinon.assert.calledOnce(apis.doSomething); 我得到` AssertError: function doSomething(_x5, _x6) { return _ref2.apply(this, arguments); } 没有被存根 `
  • 使用--require babel-polyfill

标签: node.js sinon sinon-chai


【解决方案1】:

如果您查看您的 module.exports,您会注意到没有命名函数。如果你像下面这样设置你的模块,你会注意到apis 将有一个名为doSomething 的属性,你可以存根。

module.exports = { doSomething }

【讨论】:

  • 试过了。没有任何区别。似乎仍然忽略了存根
  • 好吧,当我手动运行 apis() 或 console.log 时,我可以看到它可用且工作文件。所以不要认为没有命名出口是个问题
猜你喜欢
  • 1970-01-01
  • 2016-10-08
  • 2018-08-02
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多