matmik
matmik

Reputation: 131

expected "spy" to be called at least once Vitest

I am getting error - expected "spy" to be called at least once, when calling

expect(log.warn).toHaveBeenCalled();

I do not understand why it is happening, because the function, which I am testing is calling that function log.warn(.....)

Unit test

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();
    });
  });

Vue store action

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

Maybe somebody had this situation and somehow overcame it?

I have tried numerous different variants from vitest documentation to test this, but none helped, also haven't found solution in stackoverflow

Upvotes: 13

Views: 28123

Answers (2)

ashish singh
ashish singh

Reputation: 6914

try to spy on the function before you start your test

vi.spyOn(console, 'warn');

this essentially creates a mock for that function

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

Upvotes: 3

Sanka Sanjeeva
Sanka Sanjeeva

Reputation: 3550

I got the same error on one of my test cases.

eg:-

const mockFn = vi.fn();

vi.mock('path', async (importActual) => {
  const actual = await importActual();

  return {
    ...actual,
    myFn: mockFn,
  };
});

test('should ...', async () => {
  render(<MyComponent />);

  await user.click(screen.getByRole('button', { name: 'Click me' }));

  expect(mockFn).toBeCalled();
});

Reason is my button hasn't clicked. Maybe a reason like it is disabled or has a pointer event none.

Upvotes: -1

Related Questions