vuejs/vitest:如何测试/模拟组合函数



我有点拘泥于测试组合函数。我将vitest与@vue/test-utils一起使用,但也找不到让它与jest一起使用的好方法。

我的问题是:如何测试使用其他可组合函数的可组合函数?如何正确地模拟函数的返回值?

假设我有一个这样的作文:

import {useExternalComposition} from '@/composables/externalComposition'
export function useFoo() {
function isConditionTrue(condition) {
if (condition) {
return false;
}
return true;
}

async function bar() {
const { externalFunction1, externalFunction2} = useExternalComposition();
const isTrue = isConditionTrue(true);
try {
if (isTrue) {
await externalFunction1();
return;
} 
await externalFunction2();
} catch(e) {
console.error(e);
}
}

return {
bar, 
isConditionTrue
}
}

使用vitest,我无法找到一种方法,正确地测试bar,详细地模拟isConditionTrue、externalFunction1和externalFunction2的结果。

这是我目前最好的方法:

it('should call isConditionTrue', async function () {
const useFooVar = useFoo();
const spy = vi
.spyOn(useFooVar, 'isConditionTrue')
.mockImplementationOnce(() => true);
expect(spy.getMockName()).toEqual('isConditionTrue'); // true
await useFooVar.bar();
expect(spy).toHaveBeenCalled(); // AssertionError: expected "isConditionTrue" to be called at least once
});

我想念什么?

我尝试了多种嘲笑/间谍功能的方法,并期望有一个正确的断言

为了嘲笑我这样做:

import { composableOne } from '~/composables/composableOne';
import { describe, it, expect, afterEach, vi } from 'vitest';
describe('composableOne', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('should return true', async () => {
// composableOne uses composableTwo
vi.doMock('~/composables/composableTwo', () => {
return {
composableTwo: vi.fn().mockReturnValue('my new mocked return value'),
};
});
const { composableOne } = await import('~/composables/composableOne');
// then expect whatever you want based on the new value
expect(composableOne()).toBe(true);
});
});

请注意,您可以使用vi.mock,但这会将声明提升到文件的顶部。所以,如果你两次试图嘲笑同一件事。它不起作用。这就是我使用vi.doMock的原因,它不会提升声明,而是在下次导入可组合文件时应用mock。这就是在mock之后导入的原因,因为这个导入知道mock在它之前

更多信息点击这里

最新更新