Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!