当我尝试测试打字稿代码时:
namespace MainNamespace {
export class MainClass {
public sum(a: number, b: number) : number {
return a + b;
}
}
}
我的测试:
describe("main test", () => {
it("sum test", () => {
var mainClass = new MainNamespace.MainClass();
expect(mainClass.sum(3, 2)).toEqual(5);
})
})
我收到错误:
ReferenceError:未定义MainNamespace
如何使用Jest(ts jest)的名称空间测试代码?
答案 0 :(得分:0)
这是一个有效的示例:
index.ts
:
// tslint:disable-next-line: no-namespace
export namespace MainNamespace {
export class MainClass {
public sum(a: number, b: number): number {
return a + b;
}
}
}
index.spec.ts
:
import { MainNamespace } from './';
describe('MainNamespace', () => {
it('sum test', () => {
const mainClass = new MainNamespace.MainClass();
expect(mainClass.sum(3, 2)).toEqual(5);
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/50085505/index.spec.ts
MainNamespace
✓ sum test (7ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.713s, estimated 10s
依赖版本:
"typescript": "^3.6.4",
"jest": "^24.9.0",
"ts-jest": "^24.1.0",
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/50085505