'Can I put my jest mock in a separate file? manual mock
In my get-sites.spec.js I created a mock like this which works perfectly fine:
jest.mock('@aws-sdk/client-secrets-manager', () => {
const SecretsManagerClient = jest.fn().mockImplementation(() => {
const result = {
SecretString: "{\"server\":\"host\",\"database\":\"database\",\"user\":\"userName\",\"password\":\"password\"}"
};
return {
send: jest.fn().mockResolvedValue(result)
};
});
const GetSecretValueCommand = jest.fn().mockImplementation(() => {
return {}
});
return {
SecretsManagerClient,
GetSecretValueCommand
}
});
I've tried creating the following directory structure and moved the mock code to the client-secrets-manager.js file.
__tests__/
|- get-sites.spec.js
__mocks__/
|- @aws-sdk/
|-- client-secrets-manager.js
src/
|- get-sites.js
Then in my get-sites.spec.js file I changed the mock code to jest.mock('@aws-sdk/client-secrets-manager');
When I run the test I get an error: TypeError: Cannot read properties of undefined (reading 'SecretString'). Is there some way to move my mock to a separate file to make it available to all my unit tests that will preserve the functionality?
Solution 1:[1]
Turns out I was close. I changed the client-secrets-manager.js file in the mocks folder to look like this:
const SecretsManagerClient = jest.fn().mockImplementation(() => {
return {
send: jest.fn()
};
});
const GetSecretValueCommand = jest.fn().mockImplementation(() => {
return {}
});
module.exports = {
SecretsManagerClient,
GetSecretValueCommand
}
Then in my get-sites.spec.js file I added this line to the test:
const sendResponse = {
SecretString: "{\"server\":\"host\",\"database\":\"database\",\"user\":\"userName\",\"password\":\"password\"}"
};
jest.spyOn(SecretsManagerClient.prototype, 'send').mockResolvedValue(sendResponse);
Then I was able to assert it was called like this:
expect(SecretsManagerClient).toHaveBeenCalledTimes(1);
expect(SecretsManagerClient.prototype.send.mock.calls.length).toEqual(1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Colin |
