We have a React 17 codebase that has a ton of functions that generate mock data type save, so we can re-use them in different unit tests run by Jest.
export const createMockProject = (
overwrites: Partial<Project> = {}
): Project => ({
id: 'PROJECT_ID',
name: 'PROJECT_NAME',
transfer: jest.fn(), // mock method. Not real code, just to show the schema
...overwrites,
});
For methods, we use jest.fn(). We want to re-use those mocks in Storybook, and figured we could just set Jest globally so that when code executed in storybook that calls jest.fn() actually never calls jest.
// inside .storybook/preview.ts
// Initialize global jest.fn override
window.jest = {
fn: ((fnc: any) => fnc) as any,
};
That is a similar approach to just making jest-mock globally available, as proposed here.
The problem is that either way, React checks for jest being defined when reconciling, and throws console errors about things not being wrapped in act, which hinders any Developer to properly keep an eye on error logs while developing storybook stories.
TextField.tsx:171 Warning: An update to XComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
I saw this __DEV__ flag (see linked React code) picked up by Jest, but
- to me it is not clear what it is for, it just seems like an example
- setting it to false in the storybook setup file had no effect
- even if it worked, side effects by toggling it are not clear
I appreciate advice in how to tackle this.