typescript - 在 Jest 中,如何模拟具有依赖项的 TypeScript 类?

标签 typescript jestjs ts-jest

鉴于这个相对人为的类从 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/

相关文章:

Typescript/如何预期固定日期?

typescript - 如何在 typescript 中取消回调 hell

javascript - 如何使用 vue + vuex(或任何其他状态管理框架)处理游戏循环

typescript - 如何期望 Jest 会引发自定义错误?

jestjs - 无法模拟 createQueryBuilder 函数 typeorm Nestjs Jest

reactjs - 运行 Next.js 构建时出现 Jest 引用错误 'describe' 未定义

typescript - 在 nest.js 中处理第三方依赖项

javascript - '港口' aurelia-skeleton-navigation to typescript

linux - gatsby 站点的 Jest Watch 重启失败,且 fs/watchers 失败

jestjs - Promise.resolve 从 Jest 模拟函数返回未定义