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

115
Views
Mocking my database functions globally with jest

See original post here for more context.
tl;dr, I had a database table with some functions (createOne, findOne etc) that I managed to mock in order to do some unit testing of my API.

Now I have multiple tables and a lot more tests to write, and the solution I have now generates a lot of code duplication when mocking the database functions in every test file. Therefore, I would now like to have the mocks available globally in all my test files. I have read a lot about this on all different forums as well as checking the official docs but without success.

i have the following structure rn:

__tests__
  pages
    api
      <api tests>
src
  lib
    database
      table1.js
      table2.js
      __mocks__ (as per the official docs, this doesn't seem to work)
        table1.js
        table2.js
  pages
    api
      <files under test that calls database functions>

and then example mock:

// __mocks__/table1.js
const table1 = jest.createMockFromModule("../table1");
table1.createOne = jest.fn().mockImplementation(async () => return {id: 1});
export default table1;

// __tests__/pages/api/route1
jest.mock("src/lib/database/table1");
import {createOne} from "src/lib/database/table1";

/* rest of testing like the original post */

But the mocks aren't running correctly, and createOne is returning undefined. how do I make the mocks work globally?

about 4 years ago · Santiago Trujillo
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!