我需要在 typescript 中监视多个方法。如何在 typescript 中实现它?
// classA.ts
export class ClassA {
public methodA() {
this.methodB();
this.methodC();
return "ClassA";
}
public methodB() {}
public methodC() {}
}
// classATest.ts
import {ClassA} from './classA';
it('Sample Test', async () => {
const spyOn1 = jest.spyOn(ClassA, 'methodB');
spyOn1.mockImplementation(() => {return () => {}});
const spyOn2 = jest.spyOn(ClassA, 'methodC');
spyOn2.mockImplementation(() => {return () => {}});
const classA = new ClassA();
expect(classA.methodA()).toEqual('ClassA');
});
我收到错误说明 -
Argument of type '"methodC"' is not assignable to parameter of type '"methodB" | "prototype"'.
我们不能在一个类上使用 spyOn 多个方法吗?还有其他方法可以实现这一目标吗?
最佳答案
你需要监视methodB
和 methodC
在 ClassA.prototype
.它们是实例方法,不是 类静态方法。
例如。ClassA.ts
:
export class ClassA {
public methodA() {
this.methodB();
this.methodC();
return 'ClassA';
}
public methodB() {}
public methodC() {}
}
ClassA.test.ts
:import { ClassA } from './classA';
describe('61315546', () => {
it('Sample Test', async () => {
const spyOn1 = jest.spyOn(ClassA.prototype, 'methodB');
spyOn1.mockImplementation(() => {
return () => {};
});
const spyOn2 = jest.spyOn(ClassA.prototype, 'methodC');
spyOn2.mockImplementation(() => {
return () => {};
});
const classA = new ClassA();
expect(classA.methodA()).toEqual('ClassA');
});
});
带有覆盖率报告的单元测试结果:
PASS stackoverflow/61315546/ClassA.test.ts (12.1s)
61315546
✓ Sample Test (3ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 50 | 100 |
ClassA.ts | 100 | 100 | 50 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 13.974s
关于javascript - 是否可以在同一模块中监视(开 Jest )多个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61315546/