[英]Jest pass a mocked class to a constructor
假設我有
class A {
constructor(classB) {
}
}
class B {
}
如何在我的測試中實例化class A
並將模擬的class B
傳遞給它? 基本上我想做
a = new A(mockedClassB);
具體來說,我的問題是關於如何創建mockedClassB
以便我可以將其傳遞給 A 構造函數。
這是一個解決方案:
a.js
:
export default class A {
classB;
constructor(classB) {
this.classB = classB;
}
getName() {
return this.classB.getName();
}
}
b.js
:
export default class B {
getName() {
return 'real name from b';
}
// add a new method later
getAge() {
return 23;
}
}
a.test.js
:
import A from './a';
import B from './b';
jest.mock('./b');
describe('61596704', () => {
it('should pass', () => {
const mockedClassBInstance = new B();
mockedClassBInstance.getName.mockReturnValueOnce('mocked name from b');
const a = new A(mockedClassBInstance);
const actual = a.getName();
expect(actual).toEqual('mocked name from b');
});
it('getAge method of B should be mocked as well', () => {
const mockedClassBInstance = new B();
jest.isMockFunction(mockedClassBInstance.getAge);
});
});
單元測試結果:
PASS stackoverflow/61596704/a.test.js (8.913s)
61596704
✓ should pass (3ms)
✓ getAge method of B should be mocked as well (1ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.486s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.