typescript 如何用Jest模拟同时具有构造函数和函数的模块?

lztngnrs  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(156)

我是Jest新手,遇到了问题,我在网上找到的答案都不起作用。我需要模拟一个模块,它包含类(“Client”)和一个函数(“getCreds”)。类Client然后包含函数Login。这是我想测试的代码的外观

import * as sm from 'some-client';
const smCli: sm.Client = new sm.Client();

export const getKey = async (): void => {
    const smCreds = await sm.getCreds();
    await smCli.login(smCreds);
};

问题是,虽然我可以很容易地模拟getCreds函数,但我不知道如何模拟客户端示例的登录函数,也不知道如何正确测试getKey函数。我尝试了许多类似的行,但没有一行起作用。有人能告诉我哪里出错了吗?谢谢。

import * as sm from 'some-client';
jest.mock('some-client');

const smClientMock = sm.Client as jest.Mock<unknown>
const smGetCredsMock = sm.getCreds as jest.Mock<Promise<unknown>>

smGetCredsMock.mockResolvedValue(1);
smClientMock.mockImplementation(() => {
    return {
        login: () => {
            return 2;
        }
    };
});
x4shl7ld

x4shl7ld1#

你可以使用mockFn. mock. instances来获得sm.Client类的模拟示例,这样你就可以在示例上Assert.login()方法。
例如
some-client.ts

export class Client {
  async login(creds) {}
}

export const getCreds = async () => ({ pwd: 'real pwd' });

index.ts

import * as sm from './some-client';
const smCli: sm.Client = new sm.Client();

export const getKey = async () => {
  const smCreds = await sm.getCreds();
  await smCli.login(smCreds);
};

index.test.ts

import * as sm from './some-client';
import { getKey } from './';

jest.mock('./some-client');

const smClientMock = sm.Client as jest.MockedClass<typeof sm.Client>;
const smGetCredsMock = sm.getCreds as jest.MockedFunction<typeof sm.getCreds>;

describe('74516778', () => {
  test('should pass', async () => {
    smGetCredsMock.mockResolvedValue({ pwd: '123' });
    await getKey();
    expect(smClientMock).toBeCalledTimes(1);
    expect(smGetCredsMock).toBeCalledTimes(1);
    const smClientInstanceMock = smClientMock.mock.instances[0];
    expect(smClientInstanceMock.login).toBeCalledWith({ pwd: '123' });
  });
});

试验结果:

PASS  stackoverflow/74516778/index.test.ts (8.48 s)
  74516778
    ✓ should pass (3 ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |   76.92 |      100 |   33.33 |    87.5 |                   
 index.ts       |     100 |      100 |     100 |     100 |                   
 some-client.ts |      50 |      100 |       0 |   66.67 | 2                 
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.278 s, estimated 10 s

软件包版本:

"jest": "^26.6.3",

相关问题