如何在没有功能的NodeJ中测试模块?

时间:2018-08-01 10:22:46

标签: node.js sinon chai

我已经阅读并尝试了许多方法来执行此操作,我有一个类似于下面的模块。

//echo.js

module.exports = (services, request) => { 
  logger.debug('excecuting');
  return true;
};

我想使用sinon为该模块编写单元测试,到目前为止我一直在尝试。

describe('test', function() {
const echo1 = require('./echo');
var spy1 = sinon.spy(echo1);

beforeEach(() => {
spy1.resetHistory();
  });

it('Is function echo called once - true ', done => {
echo1(testData.mockService, testData.stubRequest); //calling module
spy1.called.should.be.true;
done();
  });
});

我得到以下输出失败,尽管我在输出窗口中看到了我的函数

1) test
   Is function echo called once - true :

  AssertionError: expected false to be true
  + expected - actual

  -false
  +true

  at Context.done (echo_unit.js:84:27)

谁能告诉我如何在nodejs中测试模块

1 个答案:

答案 0 :(得分:0)

在这种情况下,它是模块还是函数都没有关系。

未被窥视为方法的函数(同样,describe函数也不适合放置var spy1 = sinon.spy(echo1))。这里也不是必需的,因为调用函数的是您,无需测试它是否被调用。

由于echo所做的只是调用logger.debug并返回true,因此需要对此进行测试:

it('Is function echo called once - true ', () => {
  sinon.spy(logger, 'debug');
  const result = echo1(testData.mockService, testData.stubRequest);
  expect(logger.debug).to.have.been.calledWith("execute");
  expect(result).to.be(true);
  // the test is synchronous, no done() is needed
});
相关问题