簡體   English   中英

開玩笑 mocking 一個 typescript 作為依賴項導入

[英]jest mocking a typescript import as dependency

我為此搜索了很多,我看到的解決方案似乎有點老套,而且我認為應該是一個相當簡單的任務並不簡單。

我有以下 class

// 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');
          }
        };
      };
    })
  );

但它們似乎都不起作用。 有人可以對此有所了解。

這是解決方案:

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 function 使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM