簡體   English   中英

使用 sinon/nodejs 進行存根功能測試

[英]Stub function test with sinon/nodejs

我在用 sinon 繪制函數時遇到問題。

問題是返回結果或在另一個函數的函數中拋出錯誤。

如下:

服務.js

async function functionA() {
  var resultB = functionB();
}

function functionB() {
  return "FuncB";
}

module.exports = {
  functionA,
  functionB
}

服務.test.js

const { assert } = require("chai");
const sinon = require("sinon");
const service = require("./service");

it('Should return error.', async function() {
  var stub = sinon.stub(service, 'functionB').returns('functionC');
  var functionTotest = service.functionA();

  assert(stub.calledOn(functionTotest));
});

該函數沒有模擬我設置的錯誤或返回。

存根不工作,進入函數。

這是單元測試解決方案:

service.js :

async function functionA() {
  var resultB = exports.functionB();
  return resultB;
}

function functionB() {
  return 'FuncB';
}

exports.functionA = functionA;
exports.functionB = functionB;

service.test.js :

const { assert, expect } = require('chai');
const sinon = require('sinon');
const service = require('./service');

it('Should return error.', async function() {
  var stub = sinon.stub(service, 'functionB').returns('functionC');
  var actual = await service.functionA();
  expect(actual).to.be.equal('functionC');
  expect(stub.calledOnce).to.be.true;
});

帶有覆蓋率報告的單元測試結果:

  ✓ Should return error.

  1 passing (9ms)

-----------------|----------|----------|----------|----------|-------------------|
File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files        |    92.31 |      100 |    66.67 |    92.31 |                   |
 service.js      |       80 |      100 |       50 |       80 |                 7 |
 service.test.js |      100 |      100 |      100 |      100 |                   |
-----------------|----------|----------|----------|----------|-------------------|

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

暫無
暫無

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

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