javascript - Sinon Stub 单元测试

标签 javascript sinon

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

下面是要检查的代码片段:

toBeTested.js:

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

api-test.js:

const sinon = require('sinon');
const toBeTested = require('./toBeTested');
sinon.stub(toBeTested, 'getAuthenticationInfo').returns('mocked-response');
console.log(toBeTested.getAuthInfo());

我期待 console.log 输出为 mocked-response。但它给出的响应是 TEST

最佳答案

这是单元测试解决方案:

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

关于javascript - Sinon Stub 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53605161/

相关文章:

javascript - 诗农 fakeTimers 不触发

javascript - 返回未定义的 jQuery JSON

javascript - CoffeeScript 返回函数回调表现得很奇怪

javascript - ajax 调用后,curl 和 file_get_contents 不起作用

node.js - Sinon stub Mongoose 保存以解析调用保存的对象

unit-testing - 在 Angular 单元测试中模拟第三方库(Razorpay)?

javascript - 如何使用 Sinon/Qunit 模拟 'timeout' 或 'failure' 响应?

javascript - 监视函数 sinon 返回的函数

javascript - 为什么 ../file 路径在 css 和 html 中不起作用?

javascript - 如何跟踪页面上移动的 div