Javascript 如何模拟nanoid进行测试?
我试图模拟nanoid进行测试,但它似乎不起作用 我的职能Javascript 如何模拟nanoid进行测试?,javascript,typescript,jestjs,mocking,Javascript,Typescript,Jestjs,Mocking,我试图模拟nanoid进行测试,但它似乎不起作用 我的职能 public async createApp(appDto: ApplicationDto): Promise<string> { const appWithToken = { ...appDto, accessToken: nanoid() }; const application = await this.applicationModel.create(appWithToken); retu
public async createApp(appDto: ApplicationDto): Promise<string> {
const appWithToken = { ...appDto, accessToken: nanoid() };
const application = await this.applicationModel.create(appWithToken);
return application.id;
}
所以基本上我正在努力弄清楚如何模拟函数内部生成的nanoid
我在文件顶部尝试了以下操作:
jest.mock('nanoid', () => 'mock id');
然而,它根本不起作用
任何帮助都将不胜感激 您没有正确模拟模块。它使用命名导出导出nanoid
函数
使用是正确的,工厂
参数是可选的。它将创建一个模拟的nanoid
函数
此外,您可以使用ts jest/utils
中的mock
函数来处理ts类型
例如
示例.ts
:
import { nanoid } from 'nanoid';
export interface ApplicationDto {}
export class Example {
constructor(private applicationModel) {}
public async createApp(appDto: ApplicationDto): Promise<string> {
const appWithToken = { ...appDto, accessToken: nanoid() };
const application = await this.applicationModel.create(appWithToken);
return application.id;
}
}
import { nanoid } from 'nanoid';
import { Example, ApplicationDto } from './Example';
import { mocked } from 'ts-jest/utils';
jest.mock('nanoid');
const mnanoid = mocked(nanoid);
describe('67898249', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should pass', async () => {
mnanoid.mockReturnValueOnce('mock id');
const mockAppDto: ApplicationDto = { email: '123@mock.com' };
const mockApplicationModel = { create: jest.fn().mockReturnValueOnce({ id: 1 }) };
const example = new Example(mockApplicationModel);
const actual = await example.createApp(mockAppDto);
expect(actual).toEqual(1);
expect(mockApplicationModel.create).toBeCalledWith({ email: '123@mock.com', accessToken: 'mock id' });
});
});
测试结果:
PASS examples/67898249/Example.test.ts (9.134 s)
67898249
✓ should pass (4 ms)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
Example.ts | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.1 s
PASS examples/67898249/Example.test.ts (9.134 s)
67898249
✓ should pass (4 ms)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
Example.ts | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.1 s