【问题标题】:how to test a Module in NodeJs without function in it?如何在 NodeJs 中测试没有功能的模块?
【发布时间】:2018-08-01 10:22:46
【问题描述】:

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

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

【问题讨论】:

    标签: node.js sinon chai


    【解决方案1】:

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

    不能监视未作为方法调用的函数(另外,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
    });
    

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多