[英]Is it possible to spyOn (jest) multiple methods in same module?
我需要在 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"'.
Argument of type '"methodC"' is not assignable to parameter of type '"methodB" | "prototype"'.
我們不能在 class 上使用 spyOn 多種方法嗎? 還有其他方法可以實現這一目標嗎?
您需要監視ClassA.prototype
上的methodB
和methodC
。 它們是實例方法,而不是class static 方法。
例如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.