提问人:ege 提问时间:11/16/2023 更新时间:11/16/2023 访问量:18
无法通过简单的 Node 和 Typescript 设置使用 Vitest 进行模拟
Cannot get mocks working with Vitest with a simple Node and Typescript setup
问:
遵循文档备忘单,但无法让模拟与 Vitest 一起使用。
我有一个简单的文件,我在其中导出了一些功能。我想测试一个函数,该函数调用同一文件中的另一个函数。由于这是一个单元测试,我想模拟后面的。
这是设置
import { afterEach, it, describe, expect, vi, Vitest, Mock } from 'vitest';
import { logErrorWithApi, handleError } from "../../../src/functions/inqueue/queue-menu.protected";
vi.mock('../../../src/functions/inqueue/queue-menu.protected', async () => {
const original = await vi.importActual<typeof import('../../../src/functions/inqueue/queue-menu.protected')>('../../../src/functions/inqueue/queue-menu.protected');
return {
...original,
logErrorWithApi: vi.fn(),
}
});
describe(getDescribeName(__filename), () => {
afterEach(() => {
vi.resetAllMocks();
});
describe('handleError', () => {
it('should call logErrorWithApi with correct params', async () => {
const errorMock = new Error('Test error');
const contextMock = { ctx: 'test'};
const tagsMock = ['tag1', 'tag2'];
await handleError(errorMock, contextMock, tagsMock);
expect(logErrorWithApi).toHaveBeenCalledWith({
...contextMock,
message: 'Test error | stack: ' + errorMock.stack
},
['queue-menu', 'tag1', 'tag2']);
});
});
});
我在实际函数中添加了一些日志,并且它总是被调用。因此,我收到零 # 次模拟调用,测试失败。logErrorWithApi
我主要遵循这个备忘单:https://vitest.dev/guide/mocking.html#cheat-sheet 也尝试使用方法并提供实现来做到这一点。没用。spyOn
我还想知道,如果它没有被编译成 vitest 可以使用的形式,这是否可能是打字稿配置问题。这是我的打字稿配置:
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Language and Environment */
"target": "ES2017",
/* Modules */
"module": "commonjs",
"moduleResolution": "node",
"types": ["vitest/globals"],
"resolveJsonModule": true,
/* JavaScript Support */
"allowJs": true,
/* Emit */
"outDir": "./build",
/* Interop Constraints */
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
/* Type Checking */
"strict": false,
/* Completeness */
"skipLibCheck": true
}
}
答: 暂无答案
评论