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

143
Views
How to overwrite 1 function in mock automatic mock in Jest

I am transitioning the project from Javascript to Typescript. I have a helper file with javascript but the file is typescript (due to transitioning in progress). I have a helper.ts file as such (this file is 1000 long, so it's not so ez to just convert this file to typescript unfortunately)

// helper.ts
module.exports = function () {
    this.validateJwt = function(token) {
        if (token.valid) { return 200 }
        else { return 400 }
    }
    this.someOtherFunction = function () { .... /// and many more such dirty code there
}

My problem is that I want to mock this function in test, so no problem I have created a mocks folder and I just automock this in my test like this:

//__mocks__/helper.ts

 module.exports = function () {
    this.validateJwt = function(token) {
        return 200;
    }
    
}

My client class:

//client.ts
import helper from "../../helper"

module.exports.create = (event) => {
let helper = new helper();

if (helper.validateJwt(event.token) { return true }
else { return false }
}

And my test:

// test.ts
import * as helper from ('../../helper');
jest.mock('../../helper');
var client = require("../../client");

describe('client', () => {
   it('return true if token is valid', () => {
       let event = {"token": "exists"}
       expect(client.create(event)).toBe(true);
   });

   it('return false if no token', () => {
       let event = {}
       (<any>helper).validateJwt.mockImplementationOnce(() => {return 400} // not working
       expect(client.create(event)).toBe(false);  // this still returns true
   });
});

How to make my mock to override automatic mock and add this to test nr 2 so that validateJwt returns false. I am using ts files but with actual javascript in them. I tried with this:

 import * as helper from "../../helper";
 jest.mock("../../helper");

 const mockedHelper = helper as jest.Mocked<typeof helper>;

and in second test use it: mockedHelper.validateJwt.mockImplementationOnce(() => {return 400});

but it does not work (I guess because I have a function in javascript not typescript).

Any idea how to fix that (and for now rewriting this function in helper to typescript class is not an option) ?

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!