javascript - 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
,结果还是一样。
解决方案
这个对我有用。
例如
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
推荐阅读
- go - 去 httputil.ReverseProxy 不覆盖主机头
- php - Laravel 队列监听器超时
- r - 可格式化对象的粗体行名称
- python - 在 Python 3 中,单字节 (\xd0) 打印为两个字节的序列 (\xc3\x90)
- google-chrome - Windows 10 中的 chrome kiosk 模式,关闭 chrome 的正确方法
- php - 尝试在两个不同的表中输入数据时mysqli查询重复
- webrtc - 仅使用 STUN 服务器检测是否在对称 nat 后面
- go - 如何在 golang 中为我的测试用例正确创建模拟 http.request?
- python - 如何在 Python selenium 中使用 JavascriptExecutor 而不是 send_keys
- java - fabric8-maven-plugin - Dropwizard 应用程序的生成器(java-exec?)