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) ?