I'm trying to mock ontouchstart event in window object to make some tests, but i can't find a proper way to do it
export const main = () =>
!!('ontouchstart' in window || navigator.maxTouchPoints);
I try to do
it('123', () => {
const spyWindowOpen = jest.spyOn(window, 'ontouchstart');
spyWindowOpen.mockImplementation(jest.fn());
});
but ontouchstart does not seem exist on window object in my compilation tests
It's ok i do that :
describe('support ontouchstart', () => {
it('return true when window support ontouchstart event', () => {
// eslint-disable-next-line no-global-assign
window = {
ontouchstart: jest.fn(),
};
expect(!!('ontouchstart' in window)).toBe(true);
});
});
})
Please make sure to reset to window in original position back like below.
it('should render', () => {
const original = window.ontouchstart;
window.ontouchstart = jest.fn();
// rest of your code like
// expect(!!('ontouchstart' in window)).toBe(true);
window.ontouchstart = original;
});
Related
I have a code which will execute whenever we navigate thro bowser back/forward arrow click event. I need to test this event listener using the react testing library.
const useWindowPop = (switchOrg) => {
useEffect(() => {
window.onpopstate = (e) => {
if (isLoggedIn) {
const queryOrg = queryString.parse(window.location.search);
if (queryOrg?.org) {
switchOrg(queryOrg?.org);
}
}
};
}, []);
};
when I am trying to test this snippet using react-testing library, I am not able to get this event listener executed. I am trying test this like below:
it("fires history event on Window", () => {
const switchOrg = jest.fn();
renderHook(() => useWindowPop(switchOrg), {
wrapper,
});
act(() => {
fireEvent.popState(window);
});
fireEvent(
window,
new window.PopStateEvent("popstate", {
location: "/track?org=123",
state: { page: 1 },
})
);
expect(switchOrg).toHaveBeenCalled();
});
I have a React component that listen to beforeinstallprompt event to handle PWA app installation. It has an effect hook like this:
useEffect(() => {
window.addEventListener('beforeinstallprompt', handleBeforeInstallPromptEvent);
return () => {
window.removeEventListener('beforeinstallprompt', handleBeforeInstallPromptEvent);
};
}, [handleBeforeInstallPromptEvent]);
The handler handleBeforeInstallPromptEvent do some logic to show a banner asking the user to install the application if it has not already been installed.
To test this behaviour I created this jest test but it is not calling the event handler and consequently not showing the alert.
Am I missing something?
it('should render install app alert if not yet installed', async () => {
const event = createEvent('beforeinstallprompt', window, {
userChoice: new Promise((res) => res({ outcome: 'accepted', platform: '' })),
prompt: () => new Promise((res) => res(undefined)),
});
render(<InstallApp />);
await act(async () => {
fireEvent(window, event);
});
expect(screen.getByText(/Install app!/g)).toBeVisible();
});
I found the problem. The describe test block has this setup/teardown configuration that is preventing the events to be caught
beforeAll(() => {
window.addEventListener = jest.fn();
window.removeEventListener = jest.fn();
});
afterAll(() => {
(window.addEventListener as any).mockClear();
(window.removeEventListener as any).mockClear();
});
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)
I've read all of the relevant questions on this topic, and I realize this will probably be marked as a duplicate, but I simply cannot for the life of me figure out how to get this working.
I have this simple function that lazily loads elements:
export default function lazyLoad(targets, onIntersection) {
const observer = new IntersectionObserver((entries, self) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
onIntersection(entry.target);
self.unobserve(entry.target);
}
});
});
document.querySelectorAll(targets).forEach((target) => observer.observe(target));
return observer;
}
Example usage:
lazyLoad('.lazy-img', (img) => {
const pictureElement = img.parentElement;
const source = pictureElement.querySelector('.lazy-source');
source.srcset = source.getAttribute('data-srcset');
img.src = img.getAttribute('data-src');
});
Now, I'm trying to test the lazyLoad function using jest, but I obviously need to mock IntersectionObserver since it's a browser API, not a native JavaScript one.
The following works for testing the observe method:
let observe;
let unobserve;
beforeEach(() => {
observe = jest.fn();
unobserve = jest.fn();
window.IntersectionObserver = jest.fn(() => ({
observe,
unobserve,
}));
});
describe('lazyLoad utility', () => {
it('calls observe on each target', () => {
for (let i = 0; i < 3; i++) {
const target = document.createElement('img');
target.className = 'lazy-img';
document.body.appendChild(target);
}
lazyLoad(
'.lazy-img',
jest.fn(() => {})
);
expect(observe).toHaveBeenCalledTimes(3);
});
});
But I also want to test the .isIntersecting logic, where the callback fires... Except I don't know how to do that. How can I test intersections with jest?
Mocking stuff is so easy when you pass it as an argument:
export default function lazyLoad(targets, onIntersection, observerClass = IntersectionObserver) {
const observer = new observerClass(...)
...
}
// test file
let entries = [];
const observeFn = jest.fn();
const unobserveFn = jest.fn()
class MockObserver {
constructor(fn) {
fn(entries,this);
}
observe() { observeFn() }
unobserve() { unobserveFn() }
}
test('...',() => {
// set `entries` to be something so you can mock it
entries = ...something
lazyLoad('something',jest.fn(),MockObserver);
});
Another option is to use mockObserver mentioned above and mock in window.
window.IntersetionObserver = mockObserver
And you don't necessary need to pass observer in component props.
The important point to test if entries isIntesecting is to mock IntersectionObserver as class like mentioned above.
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');
});
});