Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单元测试:如何存根包装器函数_Javascript_Node.js_Mocha.js_Sinon - Fatal编程技术网

Javascript 单元测试:如何存根包装器函数

Javascript 单元测试:如何存根包装器函数,javascript,node.js,mocha.js,sinon,Javascript,Node.js,Mocha.js,Sinon,我不熟悉单元测试,并试图找出如何存根包装器函数。我用的是西农摩卡咖啡 如果我有如下函数: const user = await User.findOne({ email: email }); 我已经可以这样把它存根了: const userFindOneStub = sandbox.stub(User, 'findOne') .returns({ _id: 'userId1234', companies: [ { _id: 'companyId1234'

我不熟悉单元测试,并试图找出如何存根包装器函数。我用的是西农摩卡咖啡

如果我有如下函数:

const user = await User.findOne({ email: email });
我已经可以这样把它存根了:

const userFindOneStub = sandbox.stub(User, 'findOne')
  .returns({
    _id: 'userId1234',
    companies: [
    {
      _id: 'companyId1234'
    }
  ]
});
但我必须为我的函数创建一个包装器,以便使用Lodash对特定函数的参数进行重新排序:

const userWrapper = _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
const res = await userWrapper(someargs);

我可以存根
UserFunction
调用,但是如何在单元测试中存根
userWrapper
调用呢?

方法是将userWrapper另存为一个模块,然后进行后续操作

例如,您可以创建userWrapper.js,如下所示

// File: userWrapper.js
// This is just sample
const userWrapper = () => {
  // In your case is: _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
  console.log('real');
}
module.exports = { userWrapper };
// File: main.js
const wrapper = require('./userWrapper.js');

module.exports = async function main () {
  // In your case: const res = await userWrapper();
  wrapper.userWrapper();
}
然后,您可以在主js中使用它来实现这一点

// File: userWrapper.js
// This is just sample
const userWrapper = () => {
  // In your case is: _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
  console.log('real');
}
module.exports = { userWrapper };
// File: main.js
const wrapper = require('./userWrapper.js');

module.exports = async function main () {
  // In your case: const res = await userWrapper();
  wrapper.userWrapper();
}
最后是测试文件

// File: test.js
const sinon = require('sinon');
const wrapper = require('./userWrapper.js');
const main = require('./main.js');

it('Stub userWrapper', () => {
  const stub = sinon.stub(wrapper, 'userWrapper').callsFake(() => {
    console.log('fake');
  });

  main();

  sinon.assert.calledOnce(stub);
});
当您从终端使用mocha运行时:

$ npx mocha test.js


fake
  ✓ Stub userWrapper

  1 passing (3ms)

非常感谢。这看起来很棒,我要试试这个。如果我不再使用lodash函数,而是使用诸如“util.promisify((userID,company,jwt,callback)=>myFunction(userID,company,callback,jwt))”之类的包装器按参数重新排序,这会允许我不必为测试导入单独的文件吗?您可以使用stub.rearg或util.promisify(内部方法)代替stub-userWrapper。