0

For some reason in ViTest mocks are not replacing my real function. I have a main function here

const { handler1 } = require(./path/handler1)

exports.mainFunction = async (event) => {
 try {
    const val1 = await handler1(event)
    console.log(val1)

Handler 1 looks like

exports.handler1 = async (data) => { return "real" }

I am trying to write unit tests for mainFunction where I can mock the response from handler1 (Handler1 already has its own unit tests)

import { handler1} from '../path/handler1.js';
vi.mock('../path/handler1.js');

describe('mainFunction()', function () {
  it("should return fake")  async function () {
    let handlerMock = {
      handler1: () => "Fake",
    };
    handler1.mockResolvedValue(handlerMock);
    await mainFunction("event")
    // mainFunction is outputting real and not fake

  }
}
1
  • It could be related to cjs/esm interop. You import handler1 as named import in the test, but cjs export corresponds to esm default, I'm not sure what could happen internally, this is undocumented behaviour. Please, add vitest config to the question. You can verify if this is the cause by rewriting all the modules involved to esm and checking if this changes the way it works Commented Mar 25 at 17:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.