为此我进行了很多搜索,我认为解决方案似乎有些拙劣,对于我认为应该是一件相当简单的任务并不简单。
我有以下课程
// client.ts
export interface myClient {
getClient: (customerId: string) => Promise<string>;
}
const impClient = (): myClient => {
return {
getClient: async (customerId: string) => {
// Implementation
}
};
};
export default impClient;
我正在尝试使用默认实现来对此进行嘲笑。我尝试了很多方法,包括
jest.mock('./client', () =>
jest.fn().mockImplementation(() => {
return () => {
return {
getClient: () => {
return Promise.resolve('abcde');
}
};
};
})
);
但是它们似乎都不起作用。有人可以帮忙澄清一下吗?
答案 0 :(得分:0)
这是解决方案:
client.ts
:
export interface myClient {
getClient: (customerId: string) => Promise<string>;
}
const impClient = (): myClient => {
return {
getClient: async (customerId: string) => {
return customerId;
}
};
};
export default impClient;
main.ts
,main
函数使用impClient
import impClient from './client';
export function main(customerId) {
return impClient().getClient(customerId);
}
main.spec.ts
:
import { main } from './main';
import impClient from './client';
jest.mock('./client.ts', () => {
const mockedClient = {
getClient: jest.fn()
};
return jest.fn(() => mockedClient);
});
const client = impClient();
describe('main', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should return client correctly', async () => {
(client.getClient as jest.MockedFunction<typeof client.getClient>).mockResolvedValueOnce('abcde');
const customerId = '1';
const actualValue = await main(customerId);
expect(actualValue).toBe('abcde');
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/58107885/main.spec.ts (9.342s)
main
✓ should return client correctly (4ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
main.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.052s
以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58107885