鉴于这个相对人为的类从 Elasticsearch(或任何与此相关的数据存储)获取单个记录:
export default class UserRepoImpl implements UserRepo {
constructor(private readonly esClient: ElasticsearchClient) {}
public async getUser(id: string): Promise<User> {
const response = await this.esClient.request('GET', `/users/_doc/${id}`);
return response._source;
}
}
如何编写将实例化 UserRepoImpl
的测试对我来说,但插入一个模拟的 ElasticsearchClient 作为构造函数的参数?
最佳答案
这是单元测试解决方案:userRepoImpl.ts
:
interface User {}
interface UserRepo {
getUser(id: string): Promise<User>;
}
interface ElasticsearchClient {
request(method: string, endpoint: string): Promise<{ _source: any }>;
}
export default class UserRepoImpl implements UserRepo {
constructor(private readonly esClient: ElasticsearchClient) {}
public async getUser(id: string): Promise<User> {
const response = await this.esClient.request('GET', `/users/_doc/${id}`);
return response._source;
}
}
userRepoImpl.test.ts
:import UserRepoImpl from './userRepoImpl';
describe('62603645', () => {
it('should pass', async () => {
const mUser = { name: 'wen' };
const mEsClient = { request: jest.fn().mockResolvedValueOnce({ _source: mUser }) };
const userRepoImpl = new UserRepoImpl(mEsClient);
const actual = await userRepoImpl.getUser('1');
expect(actual).toEqual(mUser);
expect(mEsClient.request).toBeCalledWith('GET', '/users/_doc/1');
});
});
带有覆盖率报告的单元测试结果: PASS stackoverflow/62603645/userRepoImpl.test.ts (10.988s)
62603645
✓ should pass (5ms)
-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
userRepoImpl.ts | 100 | 100 | 100 | 100 |
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.27s
关于typescript - 在 Jest 中,如何模拟具有依赖项的 TypeScript 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62603645/