预计“间谍”至少被称为一次 Vitest

mat*_*mik 9 javascript vue.js vuex vite vitest

我收到错误 - 调用时预计“间谍”至少被调用一次

expect(log.warn).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生这种情况,因为我正在测试的函数正在调用该函数log.warn(.....)

单元测试

describe('handleServerError', () => {
    it('should set error message in store and log the error', () => {
      vi.mock('common/helpers/server-error-message.js', async () => {
        const actual = await vi.importActual('common/helpers/server-error-message.js');
        return {
          ...actual,
          getErrorCodeFromEvent: () => 27001,
        };
      });
      actions.handleServerError(context);
      expect(context.commit).toHaveBeenCalledWith('setServerErrorCode', 27001);
      expect(log.warn).toHaveBeenCalled();
    });
  });
Run Code Online (Sandbox Code Playgroud)

Vue 商店操作

handleServerError(context, e) {
    log.warn(getServerErrorLogMessage('getLicenses', e));
    const code = getErrorCodeFromEvent(e);
    context.commit('setServerErrorCode', code);
  },
Run Code Online (Sandbox Code Playgroud)

也许有人遇到过这种情况并以某种方式克服了它?

我已经尝试了 vitest 文档中的许多不同变体来测试这一点,但没有任何帮助,也没有在 stackoverflow 中找到解决方案

ash*_*ngh 1

在开始测试之前尝试监视该函数

vi.spyOn(console, 'warn');
Run Code Online (Sandbox Code Playgroud)

这本质上是为该函数创建一个模拟

https://vitest.dev/api/#vi-spyon