簡體   English   中英

帶有 sinon 和 chai 的節點 js 測試用例

[英]Test case for node js with sinon and chai

我正在嘗試使用 sinon 對我的節點功能之一進行單元測試。

下面是實際功能。

import { replaceYears, getFinancialYears } from './utils/years/';

const replaceAssetFileName = () => {
  const years = getFinancialYears(); // return array of years [2019, 2018, 2017]
  for (let i = 0; i < years.length; i++) {
    replaceYears(years[i], 'NEWNAME'); // replace years just replace 2019 to FY19, don't ask why a function is written for this.
  }
  return true;
};

我想模擬函數getFinancialYears ,以便僅用於測試該函數只能返回一兩年而不是 100 年。

我用 sinon 和 chai 嘗試了下面的測試用例。 但是我仍然看到函數“getFinancialYears”給出了實際的年份列表而不是假的。

it('We can replace file names', () => {
  const stub = sinon.stub(util, 'getFinancialYears').callsFake(() => ['2019']);
  expect(replaceAssetFileName()).to.be(true);
  stub.restore();
}).timeout(20000);

這是存根getFinancialYears函數的解決方案:

index.ts

import { replaceYears, getFinancialYears } from './utils/years';

export const replaceAssetFileName = () => {
  const years = getFinancialYears();
  console.log(years);
  for (let i = 0; i < years.length; i++) {
    replaceYears(years[i], 'NEWNAME');
  }
  return true;
};

utils/years.ts

export function getFinancialYears() {
  return ['2019', '2018', '2017'];
}

export function replaceYears(year, replacer) {}

index.spec.ts

import { replaceAssetFileName } from './';
import sinon from 'sinon';
import { expect } from 'chai';
import * as util from './utils/years';

describe('replaceAssetFileName', () => {
  it('We can replace file names', () => {
    const logSpy = sinon.spy(console, 'log');
    const stub = sinon.stub(util, 'getFinancialYears').callsFake(() => ['2019']);
    expect(replaceAssetFileName()).to.be.true;
    expect(logSpy.calledWith(['2019'])).to.be.true;
    stub.restore();
  });
});

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

  replaceAssetFileName
[ '2019' ]
    ✓ We can replace file names


  1 passing (10ms)

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |    95.65 |      100 |    83.33 |    95.24 |                   |
 55573978       |      100 |      100 |      100 |      100 |                   |
  index.spec.ts |      100 |      100 |      100 |      100 |                   |
  index.ts      |      100 |      100 |      100 |      100 |                   |
 55573978/utils |    66.67 |      100 |       50 |    66.67 |                   |
  years.ts      |    66.67 |      100 |       50 |    66.67 |                 2 |
----------------|----------|----------|----------|----------|-------------------|

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

暫無
暫無

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

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