In a large Vue 3 app, we have some helper modules that are imported into various components. One of these helpers returns the root node, which itself contains many other methods.
In the app calls to the methods on the root node look like this:
helpers.getRootNode().someOtherMethod(arg1);
In our Vitest environment, using a setup file, we have this helpers module mocked, with spies on each of the methods on the root node, like this:
vi.mock('@/global/helpers', () => ({
default: {
getAppNode: () => ({
someOtherMethod: vi.fn(),
}),
},
}));
I'm trying to add a unit test that verifies a component calls someOtherMethod with a specific argument, by looking at mock.calls[0][0] in my test, but no matter what I try, the mock never records any calls to it.
I'm trying to get the args like this:
const argsPassedToMock = helpers.getAppNode().someOtherError.mock.calls[0][0];
But it gives the error:
Cannot read properties of undefined (reading '0')
because calls is always an empty array.
But why is calls always empty?
I know that someOtherMethod is being called in the file under test as I added a console log after the line that calls that method, and the log is displayed when I run the test.
And I know the method is being mocked correctly because the test file runs (before I added the mock it just errored when someOtherMethod was called in the file under test), and because if I log out helpers.getAppNode().someOtherError then I see an object with methods like getMockName etc.
How can I get the args passed to the spied methods in the object returned by the globally mocked helper module?
It turns out the issue was with the original mocking of the module in the setup file. Originally we had the getAppNode method returning a simple object containing the spied methods. Changing this to a mock as well fixed the issue and the inner spies began recording their calls.
Fixed mock:
vi.mock('@/global/helpers', () => ({
default: {
getAppNode: vi.fn().mockReturnValue({ // change here
someOtherMethod: vi.fn(),
}),
},
}));