|
| 1 | +/* eslint-env jest */ |
| 2 | + |
| 3 | +import React, { useState } from 'react'; |
| 4 | +import { mount } from 'enzyme'; |
| 5 | + |
| 6 | +import { createHook } from '../../components/hook'; |
| 7 | +import defaults from '../../defaults'; |
| 8 | +import { createStore, defaultRegistry } from '../../store'; |
| 9 | +import supports from '../../utils/supported-features'; |
| 10 | +import { batch } from '../batched-updates'; |
| 11 | + |
| 12 | +const Store = createStore({ |
| 13 | + initialState: { count: 0 }, |
| 14 | + actions: { |
| 15 | + increment: () => ({ getState, setState }) => { |
| 16 | + setState({ count: getState().count + 1 }); |
| 17 | + }, |
| 18 | + }, |
| 19 | +}); |
| 20 | + |
| 21 | +const useHook = createHook(Store); |
| 22 | + |
| 23 | +describe('batch', () => { |
| 24 | + const TestComponent = ({ children }) => { |
| 25 | + const [{ count }, actions] = useHook(); |
| 26 | + const [localCount, setLocalCount] = useState(0); |
| 27 | + const update = () => |
| 28 | + batch(() => { |
| 29 | + actions.increment(); |
| 30 | + setLocalCount(localCount + 1); |
| 31 | + }); |
| 32 | + |
| 33 | + return children(update, count, localCount); |
| 34 | + }; |
| 35 | + |
| 36 | + beforeEach(() => { |
| 37 | + defaultRegistry.stores.clear(); |
| 38 | + }); |
| 39 | + |
| 40 | + it('should batch updates with scheduling disabled', () => { |
| 41 | + const child = jest.fn().mockReturnValue(null); |
| 42 | + mount(<TestComponent>{child}</TestComponent>); |
| 43 | + const update = child.mock.calls[0][0]; |
| 44 | + update(); |
| 45 | + |
| 46 | + expect(child.mock.calls).toHaveLength(2); |
| 47 | + expect(child.mock.calls[1]).toEqual([expect.any(Function), 1, 1]); |
| 48 | + }); |
| 49 | + |
| 50 | + it('should batch updates with scheduling enabled', async () => { |
| 51 | + const supportsMock = jest |
| 52 | + .spyOn(supports, 'scheduling') |
| 53 | + .mockReturnValue(true); |
| 54 | + defaults.batchUpdates = true; |
| 55 | + |
| 56 | + const child = jest.fn().mockReturnValue(null); |
| 57 | + mount(<TestComponent>{child}</TestComponent>); |
| 58 | + const update = child.mock.calls[0][0]; |
| 59 | + update(); |
| 60 | + |
| 61 | + // scheduler uses timeouts on non-browser envs |
| 62 | + await new Promise((r) => setTimeout(r, 10)); |
| 63 | + |
| 64 | + expect(child.mock.calls).toHaveLength(2); |
| 65 | + expect(child.mock.calls[1]).toEqual([expect.any(Function), 1, 1]); |
| 66 | + |
| 67 | + supportsMock.mockRestore(); |
| 68 | + defaults.batchUpdates = false; |
| 69 | + }); |
| 70 | +}); |
0 commit comments