![](/img/trans.png)
[英]In Jest, how do you mock a TypeScript class with dependencies?
[英]How do you use a jest mock in a typed test fake in typescript?
我有一個定義實現它的對象應該具有某些功能的接口。 例如:
interface MyInterface {
someFunc: () => void,
/* ... other bits and bobs */
}
我想編寫一個測試,在特定條件下調用其中一個函數。
我有一個使用測試假貨的測試,看起來像這樣:
const obj: MyInterface = {
...fakeObj,
someFunc: jest.fn(() => {})
};
/* ... the actual test code */
expect(obj.someFunc.mock.calls.length).toBe(1);
在我為obj
變量提供顯式類型之前,這是有效的。 但是,現在它產生錯誤:
屬性“mock”在類型“() => void”上不存在。
我想向我的對象添加類型,因為我希望能夠使用重構工具而不必手動修復所有測試。
當使用顯式類型時,如何編寫一個測試 function 在 object 上調用?
最簡單的方法是使用模擬測試助手。
模擬測試助手根據其源代碼的類型,提供模擬模塊的類型,甚至是它們的深層方法。 它利用最新的 TypeScript 功能,因此您甚至可以在 IDE 中完成參數類型(與 jest.MockInstance 相反)。
例如
index.ts
:
export interface MyInterface {
someFunc: () => void;
}
export function main(obj: MyInterface) {
return obj.someFunc();
}
index.test.ts
:
import { main, MyInterface } from './';
import { mocked } from 'ts-jest/utils';
describe('63478184', () => {
it('should pass', () => {
const obj: MyInterface = {
someFunc: jest.fn().mockReturnValueOnce('mocked value'),
};
main(obj);
expect(mocked(obj.someFunc).mock.calls.length).toBe(1);
});
});
帶有覆蓋率報告的單元測試結果:
PASS src/stackoverflow/63478184/index.test.ts (12.902s)
63478184
✓ should pass (8ms)
----------|----------|----------|----------|----------|-------------------|
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: 14.759s
源代碼: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63478184
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.