首页 > 解决方案 > NodeJS Mocha 不会将参数传递给函数调用

问题描述

我有以下功能:

export function ensurePathFormat(filePath: string, test = false) {
  console.log(test);
  if (!filePath || filePath === '') {
    if (test) {
      throw new Error('Invalid or empty path provided');
    } else {
      log.error('Invalid or empty path provided');
      process.exit(1);
    }
  }
}

以及 Mocha 中的以下测试用例:

describe('ensurePathFormat', () => {
  it('validates file path', () => {
    expect(() => ensurePathFormat('', true)).throws('Invalid or empty path provided');
  });
});

当然,我所有的进口都是正确的等等。

我的问题是,每次我尝试调用ensurePathFormat函数时,都会在没有传递参数的情况下调用它(第一个未定义,第二个默认为false)。

我试过在外面打电话expect,结果还是一样。

标签: javascriptnode.jstypescriptmocha.jschai

解决方案


这个对我有用。

例如

index.ts

export function ensurePathFormat(filePath: string, test = false) {
  console.log(test);
  if (!filePath || filePath === "") {
    if (test) {
      throw new Error("Invalid or empty path provided");
    } else {
      console.error("Invalid or empty path provided");
      process.exit(1);
    }
  }
}

index.test.ts

import { expect } from "chai";
import { ensurePathFormat } from "./";
import sinon from "sinon";

describe("ensurePathFormat", () => {
  it("validates file path", () => {
    expect(() => ensurePathFormat("", true)).throws("Invalid or empty path provided");
  });

  it("should print the error", () => {
    const errorLogSpy = sinon.stub(console, "error");
    const processExitSpy = sinon.stub(process, "exit");
    ensurePathFormat("");
    sinon.assert.calledWithExactly(errorLogSpy, "Invalid or empty path provided");
    sinon.assert.calledWithExactly(processExitSpy, 1);
  });
});

带有覆盖率报告的单元测试结果:

 ensurePathFormat
true
    ✓ validates file path
false
    ✓ should print the error


  2 passing (15ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |       75 |      100 |      100 |                   |
 index.test.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |       75 |      100 |      100 |                 3 |
---------------|----------|----------|----------|----------|-------------------|

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


推荐阅读