Sinon Stub单元测试

时间:2018-12-04 03:12:12

标签: javascript sinon

我写了一小段代码来了解sinon功能。

下面是要检查的代码段:

{-2*x/5}

我期望console.log输出为模拟响应。但是它以TEST作为响应。

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案:

index.js

const getAuthenticationInfo = orgId => {
  return 'TEST';
};
const getAuthToken = orgId => {
  var lmsInfo = exports.getAuthenticationInfo(orgId);
  return lmsInfo;
};

exports.getAuthenticationInfo = getAuthenticationInfo;
exports.getAuthToken = getAuthToken;

index.spec.js

const mod = require('./');
const sinon = require('sinon');
const { expect } = require('chai');

describe('53605161', () => {
  it('should stub getAuthenticationInfo correctly', () => {
    const stub = sinon.stub(mod, 'getAuthenticationInfo').returns('mocked-response');
    const actual = mod.getAuthToken(1);
    expect(actual).to.be.equal('mocked-response');
    expect(stub.calledWith(1)).to.be.true;
    stub.restore();
  });

  it('getAuthenticationInfo', () => {
    const actual = mod.getAuthenticationInfo();
    expect(actual).to.be.equal('TEST');
  });
});

具有100%覆盖率报告的单元测试结果:

 53605161
    ✓ should stub getAuthenticationInfo correctly
    ✓ getAuthenticationInfo


  2 passing (7ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.js      |      100 |      100 |      100 |      100 |                   |
 index.spec.js |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/53605161