如何在没有功能的情况下测试 NodeJs 中的模块?

how to test a Module in NodeJs without function in it?

我已经阅读并尝试了很多方法来做到这一点,我有一个如下所示的模块。

//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();
  });
});

我得到以下失败的输出,虽然我在输出中看到我的函数被调用 window

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 中测试模块

在这种情况下,它是一个模块还是一个函数并不重要。

无法侦测未作为方法调用的函数(另外,describe 函数不适合放置 var spy1 = sinon.spy(echo1))。这里也不需要,因为调用函数的是你,不需要测试它是否被调用。

由于 echo 所做的只是调用 logger.debug 和 returns 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
});