'Jest tests breaks when calling getState outside a component in React
A bunch of my tests suddenly started breaking when I use store.getState() inside a function in React. If I log the store, the store exists but it is still breaking my tests for some reason. I am sure the store.getState() function is breaking my tests because if I remove it from the formatCurrency function below, it works again. Only my tests are breaking, the application is working fine.
store.ts
import { init, RematchDispatch, RematchRootState } from '@rematch/core';
import persistPlugin from '@rematch/persist';
import storage from 'redux-persist/lib/storage';
import { RootModel, models } from './model';
export const persistKey = '@zmyle:persist';
const persistConfig = {
key: persistKey,
storage,
blacklist: ['theme', 'loading', 'app'],
};
export const store = init<RootModel>({
models,
plugins: [persistPlugin(persistConfig)],
redux: {
rootReducers: {
RESET_APP: state => {
return { app: state?.app };
},
},
},
});
export type Store = typeof store;
export type Dispatch = RematchDispatch<RootModel>;
export type RootState = RematchRootState<RootModel>;
utils/currency.ts
import { store } from 'store';
export const formatCurrency = (amount: number, minimumFractionDigits = 2) => {
if (!store || !store.getState()) return '';
// This is breaking my tests
const { currency } = store.getState().currency;
const locale = generateLocale(currency);
const stringAmount = new Intl.NumberFormat(locale, {
style: 'currency',
currency,
minimumFractionDigits,
maximumFractionDigits: 2,
}).format(amount);
return stringAmount;
};
Test setup
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
import 'jest-styled-components';
import 'services/i18n';
jest.setTimeout(120000);
window.open = jest.fn();
jest.mock('use-debounce', () => ({
useDebounce: str => [str],
}));
jest.mock('services/api', () => ({
api: {
get: jest.fn(() => {
Promise.resolve({ data: { data: {} } });
}),
post: jest.fn(() => {
Promise.resolve({ data: { data: {} } });
}),
put: jest.fn(() => {
Promise.resolve({ data: { data: {} } });
}),
delete: jest.fn(() => {
Promise.resolve({ data: { data: {} } });
}),
},
}));
beforeAll(() => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query: string): MediaQueryList => ({
media: query,
matches: query === '(pointer: fine)',
onchange: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
addListener: jest.fn(),
removeListener: jest.fn(),
dispatchEvent: () => false,
}),
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
