Here is my code:
import { it, describe, expect, vi, beforeEach } from 'vitest';
const ClientAuthenticator = require('../src/client-authenticator');
const { ssmClient, getParameterCommand } = require('../src/helpers/aws');
const ssmClientMock = vi.fn();
const getParameterCommandMock = vi.fn();
vi.mock('../src/helpers/aws', () => {
return {
ssmClient: ssmClientMock,
getParameterCommand: getParameterCommandMock,
};
});
describe('ClientAuthenticator.authenticator Tests', () => {
it('Should set correct client name', async () => {
// Arrange
console.log(ssmClient); // This logs real implementation not a mock.
const clientId = 'clientId';
const clientSecret = 'clientSecret';
... rest of the test ...
See that line that says console.log(ssmClient)
? this one prints real implementation not the mock though it should return ssmClientMock
(this happens also in the production code – it sees the real implementation not the mock.) What am I missing here? 🤔
2
Answers
It turned out that Vitest works with ES6 modules. It has no effect if you're using
require
. More details are given here: https://vitest.dev/api/vi.html#vi-mockBased on the code snippet you provided, it seems like you’re trying to mock the ssmClient and getParameterCommand functions from the ../src/helpers/aws module using the vitest library. However, when you log ssmClient in the test, it shows the real implementation instead of the mock.
One possible reason for this issue is that the ssmClient and getParameterCommand variables are imported before the mocking is applied. The import statement is executed when the module is loaded, so if the mocking is done afterwards, the original implementation will already be imported.
To fix this, you can try moving the import statement inside the test or the beforeEach block. Here’s an updated version of your code:
By re-importing the variables inside the beforeEach block, you ensure that they are imported after the mocking has been applied, and the mock implementation should be logged instead of the real implementation.
Please note that this is just one possible solution based on the code you provided. There might be other factors causing the issue, so feel free to provide more information if the problem persists.