簡體   English   中英

詩農存根單元測試

[英]Sinon Stub unit test

我寫了一小段代碼來理解 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM