Vitest 似乎没有正确模拟

问题描述 投票:0回答:1

我想我可能有点疯了。

我有以下内容

title.ts

import { useTitle } from '@vueuse/core';
import { t } from '@/helpers';

export const setTitle = (title: string): void => {
  console.log('in function', t); // -> consoles the actual function
  useTitle(t(title), {
    titleTemplate: `%s | ${import.meta.env.VITE_APP_NAME}`,
  });
};

title.spec.ts

import { describe, it, expect, vi, afterEach } from 'vitest';
import { useTitle } from '@vueuse/core';

import { setTitle } from './title';
import { t } from '@/helpers';

vi.mock('@vueuse/core', () => ({
  useTitle: vi.fn(),
}));
vi.mock('@/helpers', () => ({
  t: vi.fn(),
}));

describe('helpers: title', () => {
  afterEach(() => {
    vi.resetAllMocks();
  });

  describe('set title', () => {
    it('will set the title of the page', () => {
      t.mockImplementation(() => 'test');
      console.log('in test', t); // -> will console the spyed function
      setTitle('test');

      expect(t).toHaveBeenCalled();
      expect(useTitle).toHaveBeenCalled();
    });
  });
});

我收到以下错误

[intlify] 在“en”区域设置消息中找不到“test”键。
断言错误:预计“间谍”至少被调用一次

我一定没有正确理解这一点,但我认为模拟导入路径会导致测试模拟我正在测试的文件中的导入。

如果我将两个导入更改为

import * as helpers from '@/helpers
,测试就会运行并通过,所以我很困惑。

有人能看出这有什么问题吗?

unit-testing jestjs vitest
1个回答
0
投票

我面临着同样的问题,经过一番研究,我发现了这个 GitHub 线程。基本上,这是 vitest 中的一个错误。

https://github.com/vitest-dev/vitest/issues/4619

它被标记为已关闭,因此应该在较新版本的包中修复。

© www.soinside.com 2019 - 2024. All rights reserved.