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

296
Views
How to create an automatic mock for built-in objects? (Jest, Vanilla JS)

I know that with Jest you can create an automatic class mock for an ES6 class. You can do that by calling jest.mock() with the filename as parameter, like shown below:

import ClassThatShouldBeMocked from "./path/to/the/file.js";

jest.mock("./path/to/the/file.js");

// ClassThatShouldBeMocked is now mocked

But in my case I want to mock built-in objects like HTMLElement or CanvasRenderingContext2D. How do I get the path of such built-in objects? Is there another way to achieve an automatic mock in this case?


Currently I'm using jest.spyOn() to create an spy function for each method of this class, that is called in my code. This works but takes up much more time and effort, when I have to call many functions and methods every time.


Edit:
Im currently using:

  • jest@28.1.0
  • jest-environment-jsdom@28.1.0
  • babel-jest@28.1.0
about 4 years ago · Juan Pablo Isaza
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!