带有sinon和chai的节点js的测试用例

问题描述 投票:0回答:1

我正在尝试使用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,以便仅出于测试目的,该函数只能返回一两年而不是一百年。

我在下面用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);
node.js unit-testing sinon chai
1个回答
0
投票

这是存根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

© www.soinside.com 2019 - 2024. All rights reserved.