Dot*_*ote 7 testing vue.js vue-composition-api vitest
I\xe2\x80\x99m 有点坚持测试组合函数。我\xe2\x80\x99m 将 vitest 与 @vue/test-utils 一起使用,但也没有找到让它与 jest 一起工作的好方法。
\n我的问题是:如何测试使用其他可组合函数的可组合函数?如何正确模拟函数返回值?
\n让\xe2\x80\x99s 说我有这样的构图:
\nimport {useExternalComposition} from \'@/composables/externalComposition\'\n\nexport function useFoo() {\n function isConditionTrue(condition) {\n if (condition) {\n return false;\n }\n return true;\n }\n \n async function bar() {\n const { externalFunction1, externalFunction2} = useExternalComposition();\n const isTrue = isConditionTrue(true);\n try {\n if (isTrue) {\n await externalFunction1();\n return;\n } \n await externalFunction2();\n } catch(e) {\n console.error(e);\n }\n }\n \n return {\n bar, \n isConditionTrue\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n使用 vitest,我无法找到一种方法来正确测试 bar,详细模拟来自 isConditionTrue 和 externalFunction1 和 externalFunction2 的结果。
\n这是我目前最好的方法:
\nit(\'should call isConditionTrue\', async function () {\n const useFooVar = useFoo();\n const spy = vi\n .spyOn(useFooVar, \'isConditionTrue\')\n .mockImplementationOnce(() => true);\n\n expect(spy.getMockName()).toEqual(\'isConditionTrue\'); // true\n\n await useFooVar.bar();\n expect(spy).toHaveBeenCalled(); // AssertionError: expected "isConditionTrue" to be called at least once\n});\nRun Code Online (Sandbox Code Playgroud)\n我想念什么?
\n我尝试了多种模拟/间谍功能的方法,并期望得到正确的断言
\n为了嘲笑我正在这样做:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,您可以使用vi.mock,但这会将声明提升到文件顶部。所以如果你试图嘲笑同一件事两次。这不起作用。这就是我使用 的原因vi.doMock,它不会提升声明,而是在下次导入可组合项时应用模拟。这就是在模拟之后导入的原因,因为此导入知道它之前的模拟。
更多信息请点击此处