5

I would like to use `vi.spyOn` to monitor the call to an sideEffect function in a module to make sure is being called by another function in a module.

I did this on jest without problems but it does not seem to work on vitest.

Here is a simplified example

aModule.ts

export function a() {
  return sideEffect();
}

export function sideEffect() {
  return 'a';
}

Here is the test file:

import { vi, expect, test } from 'vitest';
import * as aModule from '../src/aModule';

test('expect "sideEffect" to be called at least once', async () => {
  const sideEffectSpy = vi.spyOn(aModule, 'sideEffect').mockReturnValue('b');
  const aSpy = vi.spyOn(aModule, 'a');

  const res = aModule.a(); // This function calls sideEffect internally.
  expect(res).toBe('b'); // This fails - it returns 'a' so the spyOn is not workng
  expect(sideEffectSpy).toHaveBeenCalled(); // This fails as well :( 
});

I did try a few variations on this, but could not make it work. Any ideas?

Thx.

micurs
  • 543
  • 4
  • 8

1 Answers1

0

Here is a workaround while waiting for this bug to be fixed: move sideEffect to a separate module, say, bModule.ts.

export function sideEffect() {
  return "a";
}

Then aModule.ts:

import { sideEffect } from './bModule';
export function a() {
  return sideEffect();
}

And aModule.test.ts:

import { vi, expect, test } from "vitest";
import * as aModule from "./aModule";
import * as bModule from "./bModule";

test('expect "sideEffect" to be called at least once', async () => {
  const sideEffectSpy = vi.spyOn(bModule, "sideEffect").mockReturnValue("b");

  const res = aModule.a(); // This function calls sideEffect internally.
  expect(res).toBe("b"); // This now passes - it returns 'b'
  expect(sideEffectSpy).toHaveBeenCalled(); // This passes as well :)
});
Tuan Pham
  • 31
  • 1
  • 5
  • From the issue, it appears that they claim it is not an issue. I have added a comment with a test case in the same issue. Can you confirm is it is the same problem? @Tuan Pham – sureshvv Aug 26 '23 at 06:32
  • I have added another issue: https://github.com/vitest-dev/vitest/issues/4023 – sureshvv Aug 26 '23 at 06:39