Jest Mocking a function implementation on a global level - javascript

I've got a utility function that looks like this:
const getTimezoneString = (): string => {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
};
Since this function is part of an app that would run on multiple new/old browsers, I wanted to test the Intl support for different platforms.
I'm looking for a way to globally define a mock implementation of the Intl object so that when I do something like:
expect(getTimezoneString()).toEquall("Africa/Nirobi")
similarly, I would change the timeZone in the implementation and test if my function returns the new timezone.
I would also like to test, what happens if the Intl object is not supported by the browser. i.e returning undefined or throwing an error probably.
I've been using jest mockImplementation method to create a mock that returns the desired output:
const IntlDateTimeFormatMock = jest
.fn(Intl.DateTimeFormat)
.mockImplementation(() => undefined);
Is there a way I can get this mock function to automatically replace the output of the Intl whenever I call my utility?

You would need to mock the Intl class (and its methods) globally, something like:
const _global = typeof global !== 'undefined' ? global : window;
beforeAll(() => {
_global.Intl = jest.fn(() =>
DateTimeFormat: () => ({ resolvedOptions: () => ({ timezone: 'Africa/Nirobi' }) }));
});
afterAll(() => {
Intl.mockClear();
});
test('it returns correct timezone string', () => {
expect(getTimezoneString()).toEqual('Africa/Nirobi')
});

For anyone going through the same problem, this is how I ended up doing it:
describe('My Utility - getTimezoneString', () => {
const originalIntl = Intl;
beforeEach(() => {
global.Intl = originalIntl;
});
afterAll(() => {
global.Intl = originalIntl;
});
it('should return Africa/Nirobi', () => {
global.Intl = {
DateTimeFormat: () => ({
resolvedOptions: jest
.fn()
.mockImplementation(() => ({ timeZone: 'Africa/Nirobi' })),
}),
} as any;
expect(getTimezoneString()).toEqual('Africa/Nirobi');
});
});

I suggest changing only the desired method of DateTimeFormat class due to possible others methods usage within an application. You can do it like so:
beforeAll(() => {
const originalDateResolvedOptions = new Intl.DateTimeFormat().resolvedOptions();
jest.spyOn(Intl.DateTimeFormat.prototype, 'resolvedOptions').mockReturnValue({
...originalDateResolvedOptions,
timeZone: 'America/Godthab',
});
});
This overwrites only the returned timeZone property (we may of course want to overwrite more, depending on our needs)

Related

Mocking module values that exports an anonymous function with Jest

I'm trying to test a module that imports from another that has a weird export structure.
I'm using javascript with node, and jest for testing.
This is basically the code structure for the exports and the tests.
// weirdModule.js
module.exports = ({param1, param2}) = {
const weirdModuleFunction = async () => {
return await someIrrelevantFunction(param1, param2);
};
return async () => {
try {
return await weirdModuleFunction();
}
catch (e) {
throw e;
}
};
}
}
// testThisModule.js
const _weirdModuleFunction = require('weirdModule.js');
const testThisFunction = () => {
const weirdModuleFunction = _weirdModuleFunction({'abc',123});
let someDataIWantToBeMockedFromWeirdModule = await weirdModuleFunction();
const resultIWantToExpect = someDataIWantToBeMockedFromWeirdModule + ' someDataForExample';
return resultIWantToExpect;
};
module.exports = { testThisFunction }
//testThisModule.test.js
const { testThisFunction } = require('testThisModule.js');
//jest mocks to return different values for weirdModule.js
it('should return some value from weirdModule + someData',()=>{
//mockImplementation for weirdModule, maybe even mockImplementationOnce for successive testing
expect(testThisFunction()).toEqual('whatIexpect1 someDataForExample');
expect(testThisFunction()).toEqual('whatIexpectWithADifferentMockImplementation someDataForExample');
});
I'd like a solution that allows me to mock what weirdModule.js returns, and to also be able to mock it so it returns different values.
I have many tests for different branches, so I need to be able to change the mock return for weirdModule so I can have data that can be used across many tests, and some for some specific tests
I CANNOT change the structure of weirdModule (I didn't design it), and I CANNOT use anything other than jest, and I don't want to use manual mocks from __mocks__
I have managed to get it to work with only one return value, but I need to be able to change it to different values. It currently works like this:
jest.mock('weirdModule.js', () => () => {
return jest.fn(() => {
return 'whatIexpect1';
});
}
How can I achieve this? I've been scratching my head for days trying to have jest play nice and not throw 'weirdModuleFunction is not a function' when trying to mock different values for different tests. Any help is appreciated.
You need to capture weirdModule.js as a mock module in your test file. To do this, add these at the beginning of testThisModule.test.js
const weirdModule = require('weirdModule.js');
jest.mock('weirdModule.js');
Now you can mock the weird module however you want, like this:
it('should return some value from weirdModule + someData', async () => {
//mockImplementation for weirdModule, maybe even mockImplementationOnce for successive testing
weirdModule.mockImplementationOnce( () => {
return () => {
return 'whatIexpect1';
};
});
expect(await testThisFunction()).toEqual('whatIexpect1 someDataForExample');
weirdModule.mockImplementationOnce( () => {
return () => {
return 'whatIexpectWithADifferentMockImplementation';
};
});
expect(await testThisFunction()).toEqual('whatIexpectWithADifferentMockImplementation someDataForExample');
});
Hope this helps!

Mock using jest moment().format is returning current date instead of mocked date

I am trying to mock moment library's format function using jest. I have following code in my test file.
app.spec.js:
jest.mock('moment', () => {
const moment = () => ({
format: () => mockedTime
});
moment.tz = {
setDefault: () => {}
};
moment.tz.setDefault('Asia/Singapore');
return moment;
});
app.js:
moment.tz.setDefault(TIMEZONE);
moment().format('YYYYMMDD');
it is generating following output:
- "date": "20190825", // mocked date
- "date": "20190827", // result value
the expected output should be:
- "date": "20190825", // mocked date
- "date": "20190825", // result value
Can anyone help me point out what's wrong with the code?
Thanks.
Mocking 'moment-timezone' instead of 'moment fixed it.
jest.mock('moment-timezone', () => {
const moment = () => ({
format: () => mockedTime
});
moment.tz = {
setDefault: () => {}
};
moment.tz.setDefault('Asia/Singapore');
return moment;
});
The available answers did not work for my case. Mocking the underlying Date.now function however did as this answer suggests: https://stackoverflow.com/a/61659370/6502003
Date.now = jest.fn(() => new Date('2020-05-13T12:33:37.000Z'));
You call format not on moment, but on the result of moment().
jest.doMock('moment', () => {
const moment = () => ({
format: () => mockedTime,
})
moment.tz = { // prevent 'Cannot read property of undefined'
setDefault: () => {},
}
return moment
});
Is this OK, or do you need more complicated mock in you app, including timezone?

Jest mock class method on a test-by-test basis

I'm trying to mock out a utility library class with a method that returns a JSON.
Actual library structure
module.exports = class Common() {
getConfig() {
return {
real: 'data'
}
}
The file under test looks like:
const Common = require('./common');
const common = new Common();
const config = common.getConfig();
...
const someFunction = function() {
// config.real is used inside this function
}
I'm trying to mock out the Common class and return a different config JSON for each Jest test.
const fileUnderTest = require('./../fileUnderTest.js');
const Common = require('./../common.js');
jest.mock('./../common.js');
describe('something', () => {
it('test one', () => {
Common.getConfig = jest.fn().mockImplementation(() => {
return {
real : 'fake' // This should be returned for test one
};
});
fileUnderTest.someFunction(); //config.real is undefined at this point
});
it('test two', () => {
Common.getConfig = jest.fn().mockImplementation(() => {
return {
real : 'fake2' // This should be returned for test two
};
});
})
})
Is it possible to set the return value from the mock class method created by the automock of common.js at the top of the test file?
I've tried to use mockReturnValueOnce() etc.
jest.mock
In this case you don't really need to auto-mock the entire common module since you are just replacing the implementation of one method so jest.mock('./../common'); isn't necessary.
Common.getConfig
getConfig is a prototype method so getConfig exists on the prototype of Common. To mock it use Common.prototype.getConfig instead of Common.getConfig.
config in fileUnderTest.js
An instance of Common gets created and config gets set to the result of calling common.getConfig() as soon as fileUnderTest runs, which happens as soon as it gets required so the mock for Common.prototype.getConfig has to be in place before you call require('./../fileUnderTest').
const Common = require('./../common');
Common.prototype.getConfig = jest.fn().mockImplementation(() => ({ real: 'fake' }));
const fileUnderTest = require('./../fileUnderTest');
describe('something', () => {
it('should test something', () => {
fileUnderTest.someFunction(); // config.real is 'fake' at this point
});
});
Update
To mock config.real differently for each test for code like this requires that the modules be reset between tests:
describe('something', () => {
afterEach(() => {
jest.resetModules(); // reset modules after each test
})
it('test one', () => {
const Common = require('./../common');
Common.prototype.getConfig = jest.fn().mockImplementation(() => ({ real: 'fake' }));
const fileUnderTest = require('./../fileUnderTest');
fileUnderTest.someFunction(); // config.real is 'fake'
});
it('test two', () => {
const Common = require('./../common');
Common.prototype.getConfig = jest.fn().mockImplementation(() => ({ real: 'fake2' }));
const fileUnderTest = require('./../fileUnderTest');
fileUnderTest.someFunction(); // config.real is 'fake2'
})
})
Resetting the modules is necessary because once a module is required it is added to the module cache and that same module gets returned each time it is required unless the modules are reset.

How To Reset Manual Mocks In Jest

I have a manual mock of crypto that looks like this:
// __mocks__/crypto.js
const crypto = jest.genMockFromModule('crypto')
const toString: Function = jest.fn(() => {
return {}.toString()
})
const mockStringable = {toString}
const update: Function = jest.fn(() => mockStringable)
const deciper = {update}
crypto.createDecipheriv = jest.fn(() => deciper)
export default crypto
Which is basically tested like this:
const crypto = require('crypto')
jest.mock('crypto')
describe('cookie-parser', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('decryptCookieValue', () => {
it('should call the crypto library correctly', () => {
const result = decryptCookieValue('test-encryption-key', 'test-encrypted-value')
expect(crypto.pbkdf2Sync).toHaveBeenCalledTimes(2)
expect(crypto.createDecipheriv).toHaveBeenCalled()
// more tests, etc, etc, etc
expect(crypto.createDecipheriv('', '', '').update).toHaveBeenCalled()
expect(result).toEqual({}.toString())
})
})
...
This works however if in that same test file, I test another method that invokes decryptCookieValue from within crypto.createDecipheriv no longer returns my mock decipher. Instead it returns undefined. For instance:
describe('cookie-parser', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('decryptCookieValue', () => {
it('should call the crypto library correctly', () => {
const result = decryptCookieValue('test-encryption-key', 'test-encrypted-value')
expect(crypto.pbkdf2Sync).toHaveBeenCalledTimes(2)
expect(crypto.createDecipheriv).toHaveBeenCalled()
expect(crypto.createDecipheriv('', '', '').update).toHaveBeenCalled()
expect(result).toEqual({}.toString())
})
})
...
...
describe('parseAuthenticationCookie', () => {
it('should create the correct object', () => {
// parseAuthenticationCookie calls decryptCookieValue internally
const result = parseAuthenticationCookie('', '') // Fails because internal call to crypto.createDecipheriv stops returning mock decipher.
expect(result).toEqual({accessToken: null})
})
})
})
I think this is an issue with resetting the manual mock because if I take that later test and move it into a file all by itself with the same surrounding test harness it works just fine.
// new test file
import crypto from 'crypto'
import { parseAuthenticationCookie } from './index'
jest.mock('crypto')
describe('cookie-parser', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('parseAuthenticationCookie', () => {
it('should create the correct object', () => {
// Works just fine now
const result = parseAuthenticationCookie('', '')
expect(result).toEqual({accessToken: null})
})
})
})
Is my assessment here correct and, if so, how do I reset the state of the manual mock after each test?
From Jest docs:
Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.
ref: https://jestjs.io/docs/en/mock-function-api#mockfnmockreset
In your example you are assuming that calling resetAllMocks will set your manual mock back and it's not.
The reason why your test works in a separate file is because jest runs each file isolated, which is nice since you can screw up only the specs living in the same file.
In your particular case something that might work is calling jest.clearAllMocks() (since this will keep the implementation and returned values).
clearMocks options is also available at the jest config object (false as default), if you want to clear all your mocks on every test, this might be handy.
Hope this help you or anyone else having having a similar issue.
Bonus tip (no quite related) If you are mocking a module that it's being used internally by other module and in some specific test you want to mock that module again with a different mock, make sure to require the module that it's using the mocked module internally again in that specific test, otherwise that module will still reference the mock you specified next to the imports statements.
Looks like the better way to test this is something on the lines of:
jest.mock('crypto')
describe('decrypt()', () => {
afterEach(() => {
jest.resetAllMocks()
})
it('returns value', () => {
const crypto = require('crypto')
const encryptedValue = 'encrypted-value'
const update = jest.fn()
const pbkdf2SyncResult = 'test result'
crypto.pbkdf2Sync = jest.fn().mockImplementation(() => {
return pbkdf2SyncResult
})
crypto.createDecipheriv = jest.fn().mockImplementation((format, key, iv) => {
expect(format).toEqual('aes-256-cbc')
expect(key).toEqual(pbkdf2SyncResult)
expect(iv).toEqual(pbkdf2SyncResult)
return {update}
})
decrypt(encryptedValue)
const inputBuffer = Buffer.from(encryptedValue, 'base64')
expect(update).toHaveBeenCalledWith(inputBuffer)
})
})
This way I don't even have to have the manual mock and I can use mockImplementationOnce if I need to have the mock reset.

How to change mock implementation on a per single test basis?

I'd like to change the implementation of a mocked dependency on a per single test basis by extending the default mock's behaviour and reverting it back to the original implementation when the next test executes.
More briefly, this is what I'm trying to achieve:
Mock dependency
Change/extend mock implementation in a single test
Revert back to original mock when next test executes
I'm currently using Jest v21. Here is what a typical test would look like:
// __mocks__/myModule.js
const myMockedModule = jest.genMockFromModule('../myModule');
myMockedModule.a = jest.fn(() => true);
myMockedModule.b = jest.fn(() => true);
export default myMockedModule;
// __tests__/myTest.js
import myMockedModule from '../myModule';
// Mock myModule
jest.mock('../myModule');
beforeEach(() => {
jest.clearAllMocks();
});
describe('MyTest', () => {
it('should test with default mock', () => {
myMockedModule.a(); // === true
myMockedModule.b(); // === true
});
it('should override myMockedModule.b mock result (and leave the other methods untouched)', () => {
// Extend change mock
myMockedModule.a(); // === true
myMockedModule.b(); // === 'overridden'
// Restore mock to original implementation with no side effects
});
it('should revert back to default myMockedModule mock', () => {
myMockedModule.a(); // === true
myMockedModule.b(); // === true
});
});
Here is what I've tried so far:
mockFn.mockImplementationOnce(fn)
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
myMockedModule.b.mockImplementationOnce(() => 'overridden');
myModule.a(); // === true
myModule.b(); // === 'overridden'
});
Pros
Reverts back to original implementation after first call
Cons
It breaks if the test calls b multiple times
It doesn't revert to original implementation until b is not called (leaking out in the next test)
jest.doMock(moduleName, factory, options)
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
jest.doMock('../myModule', () => {
return {
a: jest.fn(() => true,
b: jest.fn(() => 'overridden',
}
});
myModule.a(); // === true
myModule.b(); // === 'overridden'
});
Pros
Explicitly re-mocks on every test
Cons
Cannot define default mock implementation for all tests
Cannot extend default implementation forcing to re-declare each mocked method
Manual mocking with setter methods (as explained here)
// __mocks__/myModule.js
const myMockedModule = jest.genMockFromModule('../myModule');
let a = true;
let b = true;
myMockedModule.a = jest.fn(() => a);
myMockedModule.b = jest.fn(() => b);
myMockedModule.__setA = (value) => { a = value };
myMockedModule.__setB = (value) => { b = value };
myMockedModule.__reset = () => {
a = true;
b = true;
};
export default myMockedModule;
// __tests__/myTest.js
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
myModule.__setB('overridden');
myModule.a(); // === true
myModule.b(); // === 'overridden'
myModule.__reset();
});
Pros
Full control over mocked results
Cons
Lot of boilerplate code
Hard to maintain on long term
jest.spyOn(object, methodName)
beforeEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
// Mock myModule
jest.mock('../myModule');
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
const spy = jest.spyOn(myMockedModule, 'b').mockImplementation(() => 'overridden');
myMockedModule.a(); // === true
myMockedModule.b(); // === 'overridden'
// How to get back to original mocked value?
});
Cons
I can't revert mockImplementation back to the original mocked return value, therefore affecting the next tests
Use mockFn.mockImplementation(fn).
import { funcToMock } from './somewhere';
jest.mock('./somewhere');
beforeEach(() => {
funcToMock.mockImplementation(() => { /* default implementation */ });
// (funcToMock as jest.Mock)... in TS
});
test('case that needs a different implementation of funcToMock', () => {
funcToMock.mockImplementation(() => { /* implementation specific to this test */ });
// (funcToMock as jest.Mock)... in TS
// ...
});
A nice pattern for writing tests is to create a setup factory function that returns the data you need for testing the current module.
Below is some sample code following your second example although allows the provision of default and override values in a reusable way.
const spyReturns = returnValue => jest.fn(() => returnValue);
describe("scenario", () => {
beforeEach(() => {
jest.resetModules();
});
const setup = (mockOverrides) => {
const mockedFunctions = {
a: spyReturns(true),
b: spyReturns(true),
...mockOverrides
}
jest.doMock('../myModule', () => mockedFunctions)
return {
mockedModule: require('../myModule')
}
}
it("should return true for module a", () => {
const { mockedModule } = setup();
expect(mockedModule.a()).toEqual(true)
});
it("should return override for module a", () => {
const EXPECTED_VALUE = "override"
const { mockedModule } = setup({ a: spyReturns(EXPECTED_VALUE)});
expect(mockedModule.a()).toEqual(EXPECTED_VALUE)
});
});
It's important to say that you must reset modules that have been cached using jest.resetModules(). This can be done in beforeEach or a similar teardown function.
See jest object documentation for more info: https://jestjs.io/docs/jest-object.
Little late to the party, but if someone else is having issues with this.
We use TypeScript, ES6 and babel for react-native development.
We usually mock external NPM modules in the root __mocks__ directory.
I wanted to override a specific function of a module in the Auth class of aws-amplify for a specific test.
import { Auth } from 'aws-amplify';
import GetJwtToken from './GetJwtToken';
...
it('When idToken should return "123"', async () => {
const spy = jest.spyOn(Auth, 'currentSession').mockImplementation(() => ({
getIdToken: () => ({
getJwtToken: () => '123',
}),
}));
const result = await GetJwtToken();
expect(result).toBe('123');
spy.mockRestore();
});
Gist:
https://gist.github.com/thomashagstrom/e5bffe6c3e3acec592201b6892226af2
Tutorial:
https://medium.com/p/b4ac52a005d#19c5
When mocking a single method (when it's required to leave the rest of a class/module implementation intact) I discovered the following approach to be helpful to reset any implementation tweaks from individual tests.
I found this approach to be the concisest one, with no need to jest.mock something at the beginning of the file etc. You need just the code you see below to mock MyClass.methodName. Another advantage is that by default spyOn keeps the original method implementation but also saves all the stats (# of calls, arguments, results etc.) to test against, and keeping the default implementation is a must in some cases. So you have the flexibility to keep the default implementation or to change it with a simple addition of .mockImplementation as mentioned in the code below.
The code is in Typescript with comments highlighting the difference for JS (the difference is in one line, to be precise). Tested with Jest 26.6.
describe('test set', () => {
let mockedFn: jest.SpyInstance<void>; // void is the return value of the mocked function, change as necessary
// For plain JS use just: let mockedFn;
beforeEach(() => {
mockedFn = jest.spyOn(MyClass.prototype, 'methodName');
// Use the following instead if you need not to just spy but also to replace the default method implementation:
// mockedFn = jest.spyOn(MyClass.prototype, 'methodName').mockImplementation(() => {/*custom implementation*/});
});
afterEach(() => {
// Reset to the original method implementation (non-mocked) and clear all the mock data
mockedFn.mockRestore();
});
it('does first thing', () => {
/* Test with the default mock implementation */
});
it('does second thing', () => {
mockedFn.mockImplementation(() => {/*custom implementation just for this test*/});
/* Test utilising this custom mock implementation. It is reset after the test. */
});
it('does third thing', () => {
/* Another test with the default mock implementation */
});
});
I did not manage to define the mock inside the test itself so I discover that I could mock several results for the same service mock like this :
jest.mock("#/services/ApiService", () => {
return {
apiService: {
get: jest.fn()
.mockResolvedValueOnce({response: {value:"Value", label:"Test"}})
.mockResolvedValueOnce(null),
}
};
});
I hope it'll help someone :)
It's a very cool way I've discovered on this blog https://mikeborozdin.com/post/changing-jest-mocks-between-tests/
import { sayHello } from './say-hello';
import * as config from './config';
jest.mock('./config', () => ({
__esModule: true,
CAPITALIZE: null
}));
describe('say-hello', () => {
test('Capitalizes name if config requires that', () => {
config.CAPITALIZE = true;
expect(sayHello('john')).toBe('Hi, John');
});
test('does not capitalize name if config does not require that', () => {
config.CAPITALIZE = false;
expect(sayHello('john')).toBe('Hi, john');
});
});

Categories

Resources