devtools.test.tsx
This file
Path
tests/devtools.test.tsx
2,687 lines · 90.2 KiB · TypeScript
Last changed by
fix(devtools): correct V8 stack regex when source path contains spaces (#3531)Copilotbefore adoptionf44cecc
History of this fileTake it
The walk stopped after 200 commits: lines older than 9ba6a63 point at it.
docs: fix typos (#3042)조우혁before adoption9ba6a63
lines 1–20why, one step back1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'2import type { Mock } from 'vitest'3import { devtools, redux } from 'zustand/middleware'4import { createStore } from 'zustand/vanilla'5import type { StoreApi } from 'zustand/vanilla'67type TupleOfEqualLengthH<8 Arr extends unknown[],9 T,10 Acc extends T[],11> = Arr extends [unknown, ...infer Rest]12 ? TupleOfEqualLengthH<Rest, T, [T, ...Acc]>13 : Acc14type TupleOfEqualLength<Arr extends unknown[], T> = number extends Arr['length']15 ? T[]16 : TupleOfEqualLengthH<Arr, T, []>1718type Connection = {19 subscribers: ((message: unknown) => void)[]20 api: {chore(deps): update dev dependencies (#3309)Daishi Katobefore adoption350d9ec
line 21why, one step back21 subscribe: Mock<(f: (message: unknown) => void) => () => void>docs: fix typos (#3042)조우혁before adoption9ba6a63
lines 22–95why, one step back22 unsubscribe: Mock<any>23 send: Mock<any>24 init: Mock<any>25 error: Mock<any>26 dispatch?: Mock<any>27 }28}29const namedConnections = new Map<string | undefined, Connection>()30const unnamedConnections = new Map<string, Connection>()3132function assertAllAreDefined<T>(arr: (T | undefined)[]): asserts arr is T[] {33 if (arr.some((e) => e === undefined)) {34 throw new Error()35 }36}37function getNamedConnectionApis<Keys extends (string | undefined)[]>(38 ...keys: Keys39) {40 const apis = keys.map((k) => namedConnections.get(k)?.api)41 assertAllAreDefined(apis)42 return apis as TupleOfEqualLength<Keys, Connection['api']>43}44function getNamedConnectionSubscribers<Keys extends (string | undefined)[]>(45 ...keys: Keys46) {47 const subscribers = keys.map((k) => {48 const subs = namedConnections.get(k)?.subscribers49 if (subs?.length !== 1) throw new Error()50 return subs[0]51 })52 assertAllAreDefined(subscribers)53 return subscribers as TupleOfEqualLength<54 Keys,55 Connection['subscribers'][number]56 >57}58function getUnnamedConnectionApis<Keys extends string[]>(...keys: Keys) {59 const apis = keys.map((k) => unnamedConnections.get(k)?.api)60 assertAllAreDefined(apis)61 return apis as TupleOfEqualLength<Keys, Connection['api']>62}63function getUnnamedConnectionSubscribers<Keys extends string[]>(...keys: Keys) {64 const subscribers = keys.map((k) => {65 const subs = unnamedConnections.get(k)?.subscribers66 if (!subs) {67 throw new Error()68 }69 return subs[0]70 })71 assertAllAreDefined(subscribers)72 return subscribers as TupleOfEqualLength<73 Keys,74 Connection['subscribers'][number]75 >76}7778function getKeyFromOptions(options: any): string | undefined {79 let key: string | undefined = options?.name80 if (options?.testStore) {81 key = `${options?.name}|${options?.testStore}`82 }83 return key84}8586const extensionConnector = {87 connect: vi.fn((options: any) => {88 const key = getKeyFromOptions(options)89 //console.log('options', options)90 const areNameUndefinedMapsNeeded =91 options.testConnectionId !== undefined && options?.name === undefined92 const connectionMap = areNameUndefinedMapsNeeded93 ? unnamedConnections94 : namedConnections95 const subscribers: Connection['subscribers'] = []chore(deps): update dev dependencies (#3309)Daishi Katobefore adoption350d9ec
line 96why, one step back96 const api: Connection['api'] = {docs: fix typos (#3042)조우혁before adoption9ba6a63
lines 97–100why, one step back97 subscribe: vi.fn((f: (m: unknown) => void) => {98 subscribers.push(f)99 return () => {}100 }),feat: add devtools.cleanup() method (#3111)Hong-Kuan Wubefore adoptionb4177b3
lines 101–105why, one step back101 unsubscribe: vi.fn(() => {102 connectionMap.delete(103 areNameUndefinedMapsNeeded ? options.testConnectionId : key,104 )105 }),docs: fix typos (#3042)조우혁before adoption9ba6a63
lines 106–195why, one step back106 send: vi.fn(),107 init: vi.fn(),108 error: vi.fn(),109 }110 connectionMap.set(111 areNameUndefinedMapsNeeded ? options.testConnectionId : key,112 {113 subscribers,114 api,115 },116 )117 return api118 }),119}120;(window as any).__REDUX_DEVTOOLS_EXTENSION__ = extensionConnector121122beforeEach(() => {123 vi.resetModules()124 extensionConnector.connect.mockClear()125 namedConnections.clear()126 unnamedConnections.clear()127})128129it('connects to the extension by passing the options and initializes', async () => {130 const options = { name: 'test', foo: 'bar' }131 const initialState = { count: 0 }132 createStore(devtools(() => initialState, { enabled: true, ...options }))133134 expect(extensionConnector.connect).toHaveBeenLastCalledWith(options)135136 const [conn] = getNamedConnectionApis(options.name)137 expect(conn.init).toHaveBeenLastCalledWith(initialState)138})139140describe('If there is no extension installed...', () => {141 let savedConsoleWarn: any142 beforeEach(() => {143 savedConsoleWarn = console.warn144 console.warn = vi.fn()145 ;(window as any).__REDUX_DEVTOOLS_EXTENSION__ = undefined146 })147 afterEach(() => {148 console.warn = savedConsoleWarn149 ;(window as any).__REDUX_DEVTOOLS_EXTENSION__ = extensionConnector150 })151152 it('does not throw', async () => {153 expect(() => {154 createStore(devtools(() => ({ count: 0 })))155 }).not.toThrow()156 })157158 it('does not warn', async () => {159 createStore(devtools(() => ({ count: 0 })))160 expect(console.warn).not.toBeCalled()161 })162})163164describe('When state changes...', () => {165 it("sends { type: setStateName || 'anonymous`, ...rest } as the action with current state", async () => {166 const options = {167 name: 'testOptionsName',168 enabled: true,169 }170 const api = createStore(devtools(() => ({ count: 0, foo: 'bar' }), options))171172 api.setState({ count: 10 }, false, 'testSetStateName')173 const [connection] = getNamedConnectionApis(options.name)174 expect(connection.send).toHaveBeenLastCalledWith(175 { type: 'testSetStateName' },176 { count: 10, foo: 'bar' },177 )178179 api.setState({ count: 15 }, false, {180 type: 'testSetStateName',181 payload: 15,182 })183 expect(connection.send).toHaveBeenLastCalledWith(184 { type: 'testSetStateName', payload: 15 },185 { count: 15, foo: 'bar' },186 )187188 api.setState({ count: 5, foo: 'baz' }, true)189 expect(connection.send).toHaveBeenLastCalledWith(190 { type: 'anonymous' },191 { count: 5, foo: 'baz' },192 )193 })194})195feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e
lines 196–220why, one step back196describe('When state changes with automatic setter inferring...', () => {197 it("sends { type: setStateName || 'setCount`, ...rest } as the action with current state", async () => {198 const options = {199 name: 'testOptionsName',200 enabled: true,201 }202203 const api = createStore<{204 count: number205 setCount: (count: number) => void206 }>()(207 devtools(208 (set) => ({209 count: 0,210 setCount: (newCount: number) => {211 set({ count: newCount })212 },213 }),214 options,215 ),216 )217218 api.getState().setCount(10)219 const [connection] = getNamedConnectionApis(options.name)220 expect(connection.send).toHaveBeenLastCalledWith(test: fix for node 24 (#3278)Daishi Katobefore adoptionab5a98b
line 221why, one step back221 { type: expect.stringMatching(/^(Object\.setCount|anonymous)$/) },feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e
lines 222–224why, one step back222 { count: 10, setCount: expect.any(Function) },223 )224 })fix(devtools): support Firefox/Safari stack format in findCallerName (#3469)Siniša Bolšecbefore adoption4e9bcf0
line 225why, one step back225fix(devtools): correct V8 stack regex when source path contains spaces (#3531)Copilotbefore adoptionf44cecc
lines 226–317why, one step back226 it.each([227 {228 label: 'webpack namespace with space',229 stack: [230 ' at api.setState (webpack://devtools.ts:200:5)',231 ' at Object.increment (webpack://my app/./src/store.js:10:5)',232 ].join('\n'),233 expected: 'Object.increment',234 },235 {236 label: 'Windows path with space',237 stack: [238 ' at api.setState (C:\\app\\devtools.ts:200:5)',239 ' at increment (C:\\Program Files\\app\\store.js:10:5)',240 ].join('\n'),241 expected: 'increment',242 },243 {244 label: 'space-free path (regression)',245 stack: [246 ' at api.setState (http://localhost/devtools.ts:200:5)',247 ' at Object.setCount (http://localhost/app.ts:10:5)',248 ].join('\n'),249 expected: 'Object.setCount',250 },251 {252 label: 'async function — strips async keyword',253 stack: [254 ' at api.setState (file.js:200:5)',255 ' at async Object.increment (file.js:10:5)',256 ].join('\n'),257 expected: 'Object.increment',258 },259 {260 label: 'constructor — strips new keyword',261 stack: [262 ' at api.setState (file.js:200:5)',263 ' at new Foo (file.js:10:5)',264 ].join('\n'),265 expected: 'Foo',266 },267 ])(268 'infers caller name from V8 stack format — $label',269 ({ stack, expected }) => {270 const OriginalError = Error271 function ErrorWithV8Stack(272 ...args: ConstructorParameters<typeof OriginalError>273 ) {274 const err = new OriginalError(...args)275 Object.defineProperty(err, 'stack', {276 value: stack,277 configurable: true,278 writable: true,279 })280 return err281 }282 ErrorWithV8Stack.prototype = OriginalError.prototype283 globalThis.Error = ErrorWithV8Stack as unknown as typeof Error284285 try {286 const options = {287 name: 'testOptionsName',288 enabled: true,289 }290291 const api = createStore<{292 count: number293 setCount: (count: number) => void294 }>()(295 devtools(296 (set) => ({297 count: 0,298 setCount: (newCount: number) => {299 set({ count: newCount })300 },301 }),302 options,303 ),304 )305306 api.getState().setCount(10)307 const [connection] = getNamedConnectionApis(options.name)308 expect(connection.send).toHaveBeenLastCalledWith(309 { type: expected },310 { count: 10, setCount: expect.any(Function) },311 )312 } finally {313 globalThis.Error = OriginalError314 }315 },316 )317fix(devtools): support Firefox/Safari stack format in findCallerName (#3469)Siniša Bolšecbefore adoption4e9bcf0
lines 318–369why, one step back318 it('infers caller name from Firefox/SpiderMonkey stack format', () => {319 const geckoStack = [320 'api.setState@http://localhost/devtools.ts:200:5',321 'setCount@http://localhost/app.ts:10:5',322 ].join('\n')323324 const OriginalError = Error325 function ErrorWithGeckoStack(326 ...args: ConstructorParameters<typeof OriginalError>327 ) {328 const err = new OriginalError(...args)329 Object.defineProperty(err, 'stack', {330 value: geckoStack,331 configurable: true,332 writable: true,333 })334 return err335 }336 ErrorWithGeckoStack.prototype = OriginalError.prototype337 globalThis.Error = ErrorWithGeckoStack as unknown as typeof Error338339 try {340 const options = {341 name: 'testOptionsName',342 enabled: true,343 }344345 const api = createStore<{346 count: number347 setCount: (count: number) => void348 }>()(349 devtools(350 (set) => ({351 count: 0,352 setCount: (newCount: number) => {353 set({ count: newCount })354 },355 }),356 options,357 ),358 )359360 api.getState().setCount(10)361 const [connection] = getNamedConnectionApis(options.name)362 expect(connection.send).toHaveBeenLastCalledWith(363 { type: 'setCount' },364 { count: 10, setCount: expect.any(Function) },365 )366 } finally {367 globalThis.Error = OriginalError368 }369 })feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e
lines 370–371why, one step back370})371docs: fix typos (#3042)조우혁before adoption9ba6a63
lines 372–816why, one step back372describe('when it receives a message of type...', () => {373 describe('ACTION...', () => {374 it('does nothing', async () => {375 const initialState = { count: 0 }376 const api = createStore(devtools(() => initialState, { enabled: true }))377 const setState = vi.spyOn(api, 'setState')378379 const [subscriber] = getNamedConnectionSubscribers(undefined)380 subscriber({381 type: 'ACTION',382 payload: '{ "type": "INCREMENT" }',383 })384385 expect(api.getState()).toBe(initialState)386 expect(setState).not.toBeCalled()387 })388389 it('unless action type is __setState', async () => {390 const initialState = { count: 0 }391 const api = createStore(devtools(() => initialState, { enabled: true }))392393 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)394 connectionSubscriber({395 type: 'ACTION',396 payload: '{ "type": "__setState", "state": { "foo": "bar" } }',397 })398399 expect(api.getState()).toStrictEqual({ ...initialState, foo: 'bar' })400 })401402 it('does nothing even if there is `api.dispatch`', async () => {403 const initialState = { count: 0 }404 const api = createStore(devtools(() => initialState, { enabled: true }))405 ;(api as any).dispatch = vi.fn()406 const setState = vi.spyOn(api, 'setState')407408 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)409 connectionSubscriber({410 type: 'ACTION',411 payload: '{ "type": "INCREMENT" }',412 })413414 expect(api.getState()).toBe(initialState)415 expect(setState).not.toBeCalled()416 expect((api as any).dispatch).not.toBeCalled()417 })418419 it('dispatches with `api.dispatch` when `api.dispatchFromDevtools` is set to true', async () => {420 const initialState = { count: 0 }421 const api = createStore(devtools(() => initialState, { enabled: true }))422 ;(api as any).dispatch = vi.fn()423 ;(api as any).dispatchFromDevtools = true424 const setState = vi.spyOn(api, 'setState')425426 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)427 connectionSubscriber({428 type: 'ACTION',429 payload: '{ "type": "INCREMENT" }',430 })431432 expect(api.getState()).toBe(initialState)433 expect(setState).not.toBeCalled()434 expect((api as any).dispatch).toHaveBeenLastCalledWith({435 type: 'INCREMENT',436 })437 })438439 it('does not throw for unsupported payload', async () => {440 const initialState = { count: 0 }441 const api = createStore(devtools(() => initialState, { enabled: true }))442 ;(api as any).dispatch = vi.fn()443 ;(api as any).dispatchFromDevtools = true444 const setState = vi.spyOn(api, 'setState')445 const originalConsoleError = console.error446 console.error = vi.fn()447448 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)449 expect(() => {450 connectionSubscriber({451 type: 'ACTION',452 payload: 'this.increment()',453 })454 }).not.toThrow()455456 expect(console.error).toHaveBeenLastCalledWith(457 '[zustand devtools middleware] Could not parse the received json',458 (() => {459 try {460 JSON.parse('this.increment()')461 } catch (e) {462 return e463 }464 })(),465 )466467 expect(() => {468 connectionSubscriber({469 type: 'ACTION',470 payload: { name: 'increment', args: [] },471 })472 }).not.toThrow()473474 expect(console.error).toHaveBeenLastCalledWith(475 '[zustand devtools middleware] Unsupported action format',476 )477478 expect(api.getState()).toBe(initialState)479 expect(setState).not.toBeCalled()480 expect((api as any).dispatch).not.toBeCalled()481482 console.error = originalConsoleError483 })484 })485486 describe('DISPATCH and payload of type...', () => {487 it('RESET, it inits with initial state', async () => {488 const initialState = { count: 0 }489 const api = createStore(devtools(() => initialState, { enabled: true }))490 api.setState({ count: 1 })491492 const [connection] = getNamedConnectionApis(undefined)493 connection.send.mockClear()494 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)495 connectionSubscriber({496 type: 'DISPATCH',497 payload: { type: 'RESET' },498 })499500 expect(api.getState()).toStrictEqual(initialState)501 expect(connection.init).toHaveBeenLastCalledWith(initialState)502 expect(connection.send).not.toBeCalled()503 })504505 it('COMMIT, it inits with current state', async () => {506 const initialState = { count: 0 }507 const api = createStore(devtools(() => initialState, { enabled: true }))508 api.setState({ count: 2 })509 const currentState = api.getState()510511 const [connection] = getNamedConnectionApis(undefined)512 connection.send.mockClear()513 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)514 connectionSubscriber({515 type: 'DISPATCH',516 payload: { type: 'COMMIT' },517 })518519 expect(connection.init).toHaveBeenLastCalledWith(currentState)520 expect(connection.send).not.toBeCalled()521 })522523 describe('ROLLBACK...', () => {524 it('updates state without recording and inits with `message.state`', async () => {525 const initialState = { count: 0, increment: () => {} }526 const api = createStore(devtools(() => initialState, { enabled: true }))527 const newState = { foo: 'bar' }528529 const [connection] = getNamedConnectionApis(undefined)530 connection.send.mockClear()531 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)532 connectionSubscriber({533 type: 'DISPATCH',534 payload: { type: 'ROLLBACK' },535 state: JSON.stringify(newState),536 })537538 expect(api.getState()).toStrictEqual({ ...initialState, ...newState })539 expect(connection.init).toHaveBeenLastCalledWith({540 ...initialState,541 ...newState,542 })543 expect(connection.send).not.toBeCalled()544 })545546 it('does not throw for unparsable `message.state`', async () => {547 const increment = () => {}548 const initialState = { count: 0, increment }549 const api = createStore(devtools(() => initialState, { enabled: true }))550 const originalConsoleError = console.error551 console.error = vi.fn()552553 const [connection] = getNamedConnectionApis(undefined)554 connection.init.mockClear()555 connection.send.mockClear()556 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)557 connectionSubscriber({558 type: 'DISPATCH',559 payload: { type: 'ROLLBACK' },560 state: 'foobar',561 })562563 expect(console.error).toHaveBeenLastCalledWith(564 '[zustand devtools middleware] Could not parse the received json',565 (() => {566 try {567 JSON.parse('foobar')568 } catch (e) {569 return e570 }571 })(),572 )573 expect(api.getState()).toBe(initialState)574 expect(connection.init).not.toBeCalled()575 expect(connection.send).not.toBeCalled()576577 console.error = originalConsoleError578 })579 })580581 describe('JUMP_TO_STATE...', () => {582 const increment = () => {}583 it('updates state without recording with `message.state`', async () => {584 const initialState = { count: 0, increment }585 const api = createStore(devtools(() => initialState, { enabled: true }))586 const newState = { foo: 'bar' }587588 const [connection] = getNamedConnectionApis(undefined)589 connection.send.mockClear()590 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)591 connectionSubscriber({592 type: 'DISPATCH',593 payload: { type: 'JUMP_TO_STATE' },594 state: JSON.stringify(newState),595 })596 expect(api.getState()).toStrictEqual({ ...initialState, ...newState })597 expect(connection.send).not.toBeCalled()598 })599600 it('does not throw for unparsable `message.state`', async () => {601 const initialState = { count: 0, increment: () => {} }602 const api = createStore(devtools(() => initialState, { enabled: true }))603 const originalConsoleError = console.error604 console.error = vi.fn()605606 const [connection] = getNamedConnectionApis(undefined)607 connection.send.mockClear()608 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)609 connectionSubscriber({610 type: 'DISPATCH',611 payload: { type: 'JUMP_TO_STATE' },612 state: 'foobar',613 })614615 expect(console.error).toHaveBeenLastCalledWith(616 '[zustand devtools middleware] Could not parse the received json',617 (() => {618 try {619 JSON.parse('foobar')620 } catch (e) {621 return e622 }623 })(),624 )625 expect(api.getState()).toBe(initialState)626 expect(connection.send).not.toBeCalled()627628 console.error = originalConsoleError629 })630 })631632 describe('JUMP_TO_ACTION...', () => {633 it('updates state without recording with `message.state`', async () => {634 const initialState = { count: 0, increment: () => {} }635 const api = createStore(devtools(() => initialState, { enabled: true }))636 const newState = { foo: 'bar' }637638 const [connection] = getNamedConnectionApis(undefined)639 connection.send.mockClear()640 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)641 connectionSubscriber({642 type: 'DISPATCH',643 payload: { type: 'JUMP_TO_ACTION' },644 state: JSON.stringify(newState),645 })646 expect(api.getState()).toStrictEqual({ ...initialState, ...newState })647 expect(connection.send).not.toBeCalled()648 })649650 it('does not throw for unparsable `message.state`', async () => {651 const increment = () => {}652 const initialState = { count: 0, increment }653 const api = createStore(devtools(() => initialState, { enabled: true }))654 const originalConsoleError = console.error655 console.error = vi.fn()656657 const [connection] = getNamedConnectionApis(undefined)658 connection.send.mockClear()659 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)660 connectionSubscriber({661 type: 'DISPATCH',662 payload: { type: 'JUMP_TO_ACTION' },663 state: 'foobar',664 })665666 expect(console.error).toHaveBeenLastCalledWith(667 '[zustand devtools middleware] Could not parse the received json',668 (() => {669 try {670 JSON.parse('foobar')671 } catch (e) {672 return e673 }674 })(),675 )676 expect(api.getState()).toBe(initialState)677 expect(connection.send).not.toBeCalled()678679 console.error = originalConsoleError680 })681 })682683 it('IMPORT_STATE, it updates state without recording and inits the last computedState', async () => {684 const initialState = { count: 0, increment: () => {} }685 const api = createStore(devtools(() => initialState, { enabled: true }))686 const nextLiftedState = {687 computedStates: [{ state: { count: 4 } }, { state: { count: 5 } }],688 }689690 const [connection] = getNamedConnectionApis(undefined)691 connection.send.mockClear()692 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)693 connectionSubscriber({694 type: 'DISPATCH',695 payload: {696 type: 'IMPORT_STATE',697 nextLiftedState,698 },699 })700 expect(api.getState()).toStrictEqual({701 ...initialState,702 ...nextLiftedState.computedStates.slice(-1)[0]?.state,703 })704 expect(connection.send).toHaveBeenLastCalledWith(null, nextLiftedState)705 })706707 it('PAUSE_RECORDING, it toggles the sending of actions', async () => {708 const api = createStore(devtools(() => ({ count: 0 }), { enabled: true }))709710 api.setState({ count: 1 }, false, 'increment')711 const [connection] = getNamedConnectionApis(undefined)712 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)713 expect(connection.send).toHaveBeenLastCalledWith(714 { type: 'increment' },715 { count: 1 },716 )717 connectionSubscriber({718 type: 'DISPATCH',719 payload: { type: 'PAUSE_RECORDING' },720 })721722 api.setState({ count: 2 }, false, 'increment')723 expect(connection.send).toHaveBeenLastCalledWith(724 { type: 'increment' },725 { count: 1 },726 )727 connectionSubscriber({728 type: 'DISPATCH',729 payload: { type: 'PAUSE_RECORDING' },730 })731732 api.setState({ count: 3 }, false, 'increment')733 expect(connection.send).toHaveBeenLastCalledWith(734 { type: 'increment' },735 { count: 3 },736 )737 })738 })739})740741describe('with redux middleware', () => {742 let api: StoreApi<{743 count: number744 dispatch: (745 action: { type: 'INCREMENT' } | { type: 'DECREMENT' },746 ) => { type: 'INCREMENT' } | { type: 'DECREMENT' }747 }>748749 it('works as expected', async () => {750 api = createStore(751 devtools(752 redux(753 (754 { count },755 { type }: { type: 'INCREMENT' } | { type: 'DECREMENT' },756 ) => ({757 count: count + (type === 'INCREMENT' ? 1 : -1),758 }),759 { count: 0 },760 ),761 { enabled: true },762 ),763 )764 ;(api as any).dispatch({ type: 'INCREMENT' })765 ;(api as any).dispatch({ type: 'INCREMENT' })766 const [connection] = getNamedConnectionApis(undefined)767 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)768 connectionSubscriber({769 type: 'ACTION',770 payload: JSON.stringify({ type: 'DECREMENT' }),771 })772773 expect(connection.init.mock.calls).toMatchObject([774 [{ count: 0 }] as unknown as Record<string, unknown>,775 ])776 expect(connection.send.mock.calls).toMatchObject([777 [{ type: 'INCREMENT' }, { count: 1 }] as unknown as Record<778 string,779 unknown780 >,781 [{ type: 'INCREMENT' }, { count: 2 }] as unknown as Record<782 string,783 unknown784 >,785 [{ type: 'DECREMENT' }, { count: 1 }] as unknown as Record<786 string,787 unknown788 >,789 ])790 expect(api.getState()).toMatchObject({ count: 1 })791 })792793 it('[DEV-ONLY] warns about misusage', () => {794 const originalConsoleWarn = console.warn795 console.warn = vi.fn()796 ;(api as any).dispatch({ type: '__setState' as any })797 expect(console.warn).toHaveBeenLastCalledWith(798 '[zustand devtools middleware] "__setState" action type is reserved ' +799 'to set state from the devtools. Avoid using it.',800 )801802 console.warn = originalConsoleWarn803 })804})805806describe('different envs', () => {807 let savedConsoleWarn: any808 beforeEach(() => {809 savedConsoleWarn = console.warn810 console.warn = vi.fn()811 })812 afterEach(() => {813 console.warn = savedConsoleWarn814 })815816 it('works in non-browser env', async () => {chore: update dev dependencies (#3279)Daishi Katobefore adoption18ab9e2
lines 817–818why, one step back817 const originalWindow = globalThis.window818 globalThis.window = undefined as anydocs: fix typos (#3042)조우혁before adoption9ba6a63
lines 819–823why, one step back819820 expect(() => {821 createStore(devtools(() => ({ count: 0 }), { enabled: true }))822 }).not.toThrow()823chore: update dev dependencies (#3279)Daishi Katobefore adoption18ab9e2
line 824why, one step back824 globalThis.window = originalWindowdocs: fix typos (#3042)조우혁before adoption9ba6a63
lines 825–827why, one step back825 })826827 it('works in react native env', async () => {chore: update dev dependencies (#3279)Daishi Katobefore adoption18ab9e2
lines 828–829why, one step back828 const originalWindow = globalThis.window829 globalThis.window = {} as anydocs: fix typos (#3042)조우혁before adoption9ba6a63
lines 830–834why, one step back830831 expect(() => {832 createStore(devtools(() => ({ count: 0 }), { enabled: true }))833 }).not.toThrow()834chore: update dev dependencies (#3279)Daishi Katobefore adoption18ab9e2
line 835why, one step back835 globalThis.window = originalWindowdocs: fix typos (#3042)조우혁before adoption9ba6a63
lines 836–1621why, one step back836 })837})838839it('preserves isRecording after setting from devtools', async () => {840 const api = createStore(devtools(() => ({ count: 0 }), { enabled: true }))841 const [connection] = getNamedConnectionApis(undefined)842 const [connectionSubscriber] = getNamedConnectionSubscribers(undefined)843 connectionSubscriber({844 type: 'DISPATCH',845 payload: { type: 'PAUSE_RECORDING' },846 })847 connectionSubscriber({848 type: 'ACTION',849 payload: '{ "type": "__setState", "state": { "foo": "bar" } }',850 })851852 api.setState({ count: 1 })853 expect(connection.send).not.toBeCalled()854})855856/* features:857 * [] if name is undefined - use multiple devtools connections.858 * [] if name and store is defined - use connection for specific 'name'.859 * [] if two stores are connected to one 'name' group and.860 * another connected to another 'name' group, then feature should work861 * [] check actions with this feature, for multiple stores that store prefixes are added -862 * [] - reset863 * [] - commit864 * [] - rollback865 * [] - jump to state, jump to action866 * [] - import state867 **/868869describe('when redux connection was called on multiple stores with `name` undefined in `devtools` options', () => {870 it('should create separate connection for each devtools store with .connect call', async () => {871 const options1 = { foo: 'bar', testConnectionId: 'asdf' }872 const options2 = { foo: 'barr', testConnectionId: '123asd' }873 const initialState1 = { count: 0 }874 const initialState2 = { count1: 1 }875876 createStore(devtools(() => initialState1, { enabled: true, ...options1 }))877 createStore(devtools(() => initialState2, { enabled: true, ...options2 }))878879 expect(extensionConnector.connect).toHaveBeenNthCalledWith(1, options1)880 expect(extensionConnector.connect).toHaveBeenNthCalledWith(2, options2)881 })882883 it('should call .init on each different connection object', async () => {884 const options1 = { foo: 'bar', testConnectionId: 'asdf' }885 const options2 = { foo: 'barr', testConnectionId: '123asd' }886 const initialState1 = { count: 0 }887 const initialState2 = { count1: 1 }888889 createStore(devtools(() => initialState1, { enabled: true, ...options1 }))890 createStore(devtools(() => initialState2, { enabled: true, ...options2 }))891892 const [conn1, conn2] = getUnnamedConnectionApis(893 options1.testConnectionId,894 options2.testConnectionId,895 )896 expect(conn1.init).toHaveBeenCalledWith(initialState1)897 expect(conn2.init).toHaveBeenCalledWith(initialState2)898 })899900 describe('when `store` property was provided in `devtools` call in options', () => {901 it('should create single connection for all internal calls of .connect and `store` is not passed to .connect', async () => {902 const { devtools: newDevtools } = await import('zustand/middleware')903904 const options1 = { store: 'store1123', foo: 'bar1' }905 const options2 = { store: 'store2313132', foo: 'bar2' }906 const initialState1 = { count: 0 }907 const initialState2 = { count1: 1 }908909 createStore(910 newDevtools(() => initialState1, { enabled: true, ...options1 }),911 )912 createStore(913 newDevtools(() => initialState2, { enabled: true, ...options2 }),914 )915916 expect(extensionConnector.connect).toHaveBeenCalledTimes(1)917 expect(extensionConnector.connect).toHaveBeenCalledWith({918 foo: options1.foo,919 })920 })921922 it('should call `.init` on single connection with combined states after each `create(devtools` call', async () => {923 const { devtools: newDevtools } = await import('zustand/middleware')924925 const options1 = { store: 'store12' }926 const options2 = { store: 'store21' }927 const initialState1 = { count1: 0 }928 const initialState2 = { count2: 1 }929930 createStore(931 newDevtools(() => initialState1, { enabled: true, ...options1 }),932 )933 createStore(934 newDevtools(() => initialState2, { enabled: true, ...options2 }),935 )936937 expect(extensionConnector.connect).toHaveBeenCalledTimes(1)938 const [connection] = getNamedConnectionApis(undefined)939 expect(connection.init).toHaveBeenCalledTimes(2)940 expect(connection.init).toHaveBeenNthCalledWith(1, {941 [options1.store]: initialState1,942 })943 expect(connection.init).toHaveBeenNthCalledWith(2, {944 [options1.store]: initialState1,945 [options2.store]: initialState2,946 })947 })948 })949})950951describe('when redux connection was called on multiple stores with `name` provided in `devtools` options', () => {952 describe('when same `name` is provided to all stores in devtools options', () => {953 it('should call .connect of redux extension with `name` that was passed from `devtools` options', async () => {954 const connectionName = 'test'955 const options1 = { name: connectionName, store: 'store1123', foo: 'bar1' }956 const options2 = { name: connectionName, store: 'store1414', foo: 'bar1' }957 const initialState1 = { count: 0 }958 const initialState2 = { count: 2 }959960 createStore(devtools(() => initialState1, { enabled: true, ...options1 }))961 createStore(devtools(() => initialState2, { enabled: true, ...options2 }))962963 expect(extensionConnector.connect).toHaveBeenCalledTimes(1)964 expect(extensionConnector.connect).toHaveBeenCalledWith({965 foo: options1.foo,966 name: connectionName,967 })968 })969 })970971 describe('when different `name` props were provided for different group of stores in devtools options', () => {972 it('should call .connect of redux extension with `name` that was passed from `devtools` options', async () => {973 const connectionNameGroup1 = 'test1'974 const connectionNameGroup2 = 'test2'975 const options1 = {976 name: connectionNameGroup1,977 store: 'store1123',978 foo: 'bar2',979 }980 const options2 = {981 name: connectionNameGroup1,982 store: 'store1232',983 foo: 'bar3',984 }985 const options3 = {986 name: connectionNameGroup2,987 store: 'store61661',988 foo: 'bar4',989 }990 const options4 = {991 name: connectionNameGroup2,992 store: 'store14632',993 foo: 'bar5',994 }995 const initialState1 = { count: 0 }996 const initialState2 = { count: 2 }997 const initialState3 = { count: 5 }998 const initialState4 = { count: 7 }9991000 createStore(devtools(() => initialState1, { enabled: true, ...options1 }))1001 createStore(devtools(() => initialState2, { enabled: true, ...options2 }))1002 createStore(devtools(() => initialState3, { enabled: true, ...options3 }))1003 createStore(devtools(() => initialState4, { enabled: true, ...options4 }))10041005 expect(extensionConnector.connect).toHaveBeenCalledTimes(2)1006 expect(extensionConnector.connect).toHaveBeenNthCalledWith(1, {1007 foo: options1.foo,1008 name: connectionNameGroup1,1009 })1010 expect(extensionConnector.connect).toHaveBeenNthCalledWith(2, {1011 foo: options3.foo,1012 name: connectionNameGroup2,1013 })1014 })10151016 it('should call `.init` on single connection with combined states after each `create(devtools` call', async () => {1017 const { devtools: newDevtools } = await import('zustand/middleware')1018 const connectionNameGroup1 = 'test1'1019 const connectionNameGroup2 = 'test2'1020 const options1 = {1021 name: connectionNameGroup1,1022 store: 'store1123',1023 foo: 'bar2',1024 }1025 const options2 = {1026 name: connectionNameGroup1,1027 store: 'store1232',1028 foo: 'bar3',1029 }1030 const options3 = {1031 name: connectionNameGroup2,1032 store: 'store61661',1033 foo: 'bar4',1034 }1035 const options4 = {1036 name: connectionNameGroup2,1037 store: 'store14632',1038 foo: 'bar5',1039 }1040 const initialState1 = { count: 0 }1041 const initialState2 = { count: 2 }1042 const initialState3 = { count: 5 }1043 const initialState4 = { count: 7 }10441045 createStore(1046 newDevtools(() => initialState1, { enabled: true, ...options1 }),1047 )1048 createStore(1049 newDevtools(() => initialState2, { enabled: true, ...options2 }),1050 )1051 createStore(1052 newDevtools(() => initialState3, { enabled: true, ...options3 }),1053 )1054 createStore(1055 newDevtools(() => initialState4, { enabled: true, ...options4 }),1056 )10571058 expect(extensionConnector.connect).toHaveBeenCalledTimes(2)1059 const [connection1, connection2] = getNamedConnectionApis(1060 connectionNameGroup1,1061 connectionNameGroup2,1062 )1063 expect(connection1.init).toHaveBeenCalledTimes(2)1064 expect(connection1.init).toHaveBeenNthCalledWith(1, {1065 [options1.store]: initialState1,1066 })1067 expect(connection1.init).toHaveBeenNthCalledWith(2, {1068 [options1.store]: initialState1,1069 [options2.store]: initialState2,1070 })1071 expect(connection2.init).toHaveBeenCalledTimes(2)1072 expect(connection2.init).toHaveBeenNthCalledWith(1, {1073 [options3.store]: initialState3,1074 })1075 expect(connection2.init).toHaveBeenNthCalledWith(2, {1076 [options3.store]: initialState3,1077 [options4.store]: initialState4,1078 })1079 })10801081 it('preserves isRecording after setting from devtools on proper connection subscriber', async () => {1082 const options1 = { name: 'asdf1' }1083 const options2 = { name: 'asdf2' }1084 const api1 = createStore(1085 devtools(() => ({ count: 0 }), { enabled: true, ...options1 }),1086 )1087 createStore(1088 devtools(() => ({ count: 0 }), { enabled: true, ...options2 }),1089 )1090 const connections = getNamedConnectionApis(options1.name, options2.name)1091 const [connectionSubscriber] = getNamedConnectionSubscribers(1092 options1.name,1093 )1094 connectionSubscriber({1095 type: 'DISPATCH',1096 payload: { type: 'PAUSE_RECORDING' },1097 })1098 connectionSubscriber({1099 type: 'ACTION',1100 payload: '{ "type": "__setState", "state": { "foo": "bar" } }',1101 })11021103 api1.setState({ count: 1 })1104 connections.forEach((conn) => expect(conn.send).not.toBeCalled())1105 })11061107 describe('with redux middleware', () => {1108 let api1: StoreApi<{1109 count: number1110 dispatch: (1111 action: { type: 'INCREMENT' } | { type: 'DECREMENT' },1112 ) => { type: 'INCREMENT' } | { type: 'DECREMENT' }1113 }>1114 let api2: StoreApi<{1115 count: number1116 dispatch: (1117 action: { type: 'INCREMENT' } | { type: 'DECREMENT' },1118 ) => { type: 'INCREMENT' } | { type: 'DECREMENT' }1119 }>11201121 it('works as expected', async () => {1122 const options1 = { testConnectionId: 'asdf' }1123 const options2 = { testConnectionId: '2f' }1124 api1 = createStore(1125 devtools(1126 redux(1127 (1128 { count },1129 { type }: { type: 'INCREMENT' } | { type: 'DECREMENT' },1130 ) => ({1131 count: count + (type === 'INCREMENT' ? 1 : -1),1132 }),1133 { count: 0 },1134 ),1135 { enabled: true, ...options1 },1136 ),1137 )1138 api2 = createStore(1139 devtools(1140 redux(1141 (1142 { count },1143 { type }: { type: 'INCREMENT' } | { type: 'DECREMENT' },1144 ) => ({1145 count: count + (type === 'INCREMENT' ? 1 : -1),1146 }),1147 { count: 10 },1148 ),1149 { enabled: true, ...options2 },1150 ),1151 )1152 ;(api1 as any).dispatch({ type: 'INCREMENT' })1153 ;(api1 as any).dispatch({ type: 'INCREMENT' })1154 ;(api2 as any).dispatch({ type: 'INCREMENT' })1155 ;(api2 as any).dispatch({ type: 'INCREMENT' })1156 const [connection1, connection2] = getUnnamedConnectionApis(1157 options1.testConnectionId,1158 options2.testConnectionId,1159 )1160 const [connectionSubscriber1, connectionSubscriber2] =1161 getUnnamedConnectionSubscribers(1162 options1.testConnectionId,1163 options2.testConnectionId,1164 )1165 connectionSubscriber1({1166 type: 'ACTION',1167 payload: JSON.stringify({ type: 'DECREMENT' }),1168 })1169 connectionSubscriber2({1170 type: 'ACTION',1171 payload: JSON.stringify({ type: 'DECREMENT' }),1172 })11731174 expect(connection1.init.mock.calls).toMatchObject([1175 [{ count: 0 }] as unknown as Record<string, unknown>,1176 ])1177 expect(connection2.init.mock.calls).toMatchObject([1178 [{ count: 10 }] as unknown as Record<string, unknown>,1179 ])1180 expect(connection1.send.mock.calls).toMatchObject([1181 [{ type: 'INCREMENT' }, { count: 1 }] as unknown as Record<1182 string,1183 unknown1184 >,1185 [{ type: 'INCREMENT' }, { count: 2 }] as unknown as Record<1186 string,1187 unknown1188 >,1189 [{ type: 'DECREMENT' }, { count: 1 }] as unknown as Record<1190 string,1191 unknown1192 >,1193 ])1194 expect(connection2.send.mock.calls).toMatchObject([1195 [{ type: 'INCREMENT' }, { count: 11 }] as unknown as Record<1196 string,1197 unknown1198 >,1199 [{ type: 'INCREMENT' }, { count: 12 }] as unknown as Record<1200 string,1201 unknown1202 >,1203 [{ type: 'DECREMENT' }, { count: 11 }] as unknown as Record<1204 string,1205 unknown1206 > as unknown as Record<string, unknown>,1207 ])1208 expect(api1.getState()).toMatchObject({ count: 1 })1209 expect(api2.getState()).toMatchObject({ count: 11 })1210 })1211 })1212 })1213})12141215describe('when create devtools was called multiple times with `name` option undefined', () => {1216 describe('When state changes...', () => {1217 it("sends { type: setStateName || 'anonymous`, ...rest } as the action with current state, isolated from other connections", async () => {1218 const options1 = {1219 enabled: true,1220 testConnectionId: '123',1221 }1222 const options2 = {1223 enabled: true,1224 testConnectionId: '324',1225 }1226 const options3 = {1227 enabled: true,1228 testConnectionId: '412',1229 }1230 const api1 = createStore(1231 devtools(() => ({ count: 0, foo: 'bar' }), options1),1232 )1233 createStore(devtools(() => ({ count: 0, foo: 'bar1' }), options2))1234 createStore(devtools(() => ({ count: 0, foo: 'bar2' }), options3))12351236 api1.setState({ count: 10 }, false, 'testSetStateName')1237 const [connection1, connection2, connection3] = getUnnamedConnectionApis(1238 options1.testConnectionId,1239 options2.testConnectionId,1240 options3.testConnectionId,1241 )1242 expect(connection1.send).toHaveBeenLastCalledWith(1243 { type: 'testSetStateName' },1244 { count: 10, foo: 'bar' },1245 )1246 expect(connection2.send).not.toBeCalled()1247 expect(connection3.send).not.toBeCalled()12481249 api1.setState({ count: 15 }, false, {1250 type: 'testSetStateName',1251 payload: 15,1252 })1253 expect(connection1.send).toHaveBeenLastCalledWith(1254 { type: 'testSetStateName', payload: 15 },1255 { count: 15, foo: 'bar' },1256 )1257 expect(connection2.send).not.toBeCalled()1258 expect(connection3.send).not.toBeCalled()12591260 api1.setState({ count: 5, foo: 'baz' }, true)1261 expect(connection1.send).toHaveBeenLastCalledWith(1262 { type: 'anonymous' },1263 { count: 5, foo: 'baz' },1264 )1265 expect(connection2.send).not.toBeCalled()1266 expect(connection3.send).not.toBeCalled()1267 })1268 })12691270 describe('when it receives a message of type...', () => {1271 describe('ACTION...', () => {1272 it('does nothing, connections isolated from each other', async () => {1273 const options1 = { testConnectionId: '123' }1274 const options2 = { testConnectionId: '231' }1275 const options3 = { testConnectionId: '4342' }1276 const initialState1 = { count: 0 }1277 const initialState2 = { count: 2 }1278 const initialState3 = { count: 3 }1279 const api1 = createStore(1280 devtools(() => initialState1, {1281 enabled: true,1282 ...options1,1283 }),1284 )1285 const api2 = createStore(1286 devtools(() => initialState2, {1287 enabled: true,1288 ...options2,1289 }),1290 )1291 const api3 = createStore(1292 devtools(() => initialState3, {1293 enabled: true,1294 ...options3,1295 }),1296 )1297 const setState1 = vi.spyOn(api1, 'setState')1298 const setState2 = vi.spyOn(api2, 'setState')1299 const setState3 = vi.spyOn(api3, 'setState')13001301 const [subscriber] = getUnnamedConnectionSubscribers(1302 options1.testConnectionId,1303 )1304 subscriber({1305 type: 'ACTION',1306 payload: '{ "type": "INCREMENT" }',1307 })13081309 expect(api1.getState()).toBe(initialState1)1310 expect(api2.getState()).toBe(initialState2)1311 expect(api3.getState()).toBe(initialState3)1312 expect(setState1).not.toBeCalled()1313 expect(setState2).not.toBeCalled()1314 expect(setState3).not.toBeCalled()1315 })13161317 it('unless action type is __setState, connections isolated from each other', async () => {1318 const options1 = { testConnectionId: 'asdf' }1319 const options2 = { testConnectionId: '2f' }1320 const options3 = { testConnectionId: 'd2e' }1321 const initialState1 = { count: 0 }1322 const initialState2 = { count: 2 }1323 const initialState3 = { count: 5 }1324 const api1 = createStore(1325 devtools(() => initialState1, { enabled: true, ...options1 }),1326 )1327 const api2 = createStore(1328 devtools(() => initialState2, { enabled: true, ...options2 }),1329 )1330 const api3 = createStore(1331 devtools(() => initialState3, { enabled: true, ...options3 }),1332 )13331334 const [connectionSubscriber] = getUnnamedConnectionSubscribers(1335 options1.testConnectionId,1336 )1337 connectionSubscriber({1338 type: 'ACTION',1339 payload: '{ "type": "__setState", "state": { "foo": "bar" } }',1340 })13411342 expect(api1.getState()).toStrictEqual({ ...initialState1, foo: 'bar' })1343 expect(api2.getState()).toStrictEqual({ ...initialState2 })1344 expect(api3.getState()).toStrictEqual({ ...initialState3 })1345 })13461347 it('does nothing even if there is `api.dispatch`, connections isolated from each other', async () => {1348 const options1 = { testConnectionId: 'asdf' }1349 const options2 = { testConnectionId: '2f' }1350 const options3 = { testConnectionId: 'd2e' }1351 const initialState1 = { count: 0 }1352 const initialState2 = { count: 2 }1353 const initialState3 = { count: 5 }1354 const api1 = createStore(1355 devtools(() => initialState1, { enabled: true, ...options1 }),1356 )1357 const api2 = createStore(1358 devtools(() => initialState2, { enabled: true, ...options2 }),1359 )1360 const api3 = createStore(1361 devtools(() => initialState3, { enabled: true, ...options3 }),1362 )1363 ;(api1 as any).dispatch = vi.fn()1364 ;(api2 as any).dispatch = vi.fn()1365 ;(api3 as any).dispatch = vi.fn()1366 const setState1 = vi.spyOn(api1, 'setState')1367 const setState2 = vi.spyOn(api2, 'setState')1368 const setState3 = vi.spyOn(api3, 'setState')13691370 const subscribers = getUnnamedConnectionSubscribers(1371 options1.testConnectionId,1372 options2.testConnectionId,1373 options3.testConnectionId,1374 )1375 const testPayload = {1376 type: 'ACTION',1377 payload: '{ "type": "INCREMENT" }',1378 }1379 subscribers.forEach((sub) => sub(testPayload))13801381 expect(api1.getState()).toBe(initialState1)1382 expect(api2.getState()).toBe(initialState2)1383 expect(api3.getState()).toBe(initialState3)1384 expect(setState1).not.toBeCalled()1385 expect(setState2).not.toBeCalled()1386 expect(setState3).not.toBeCalled()1387 expect((api1 as any).dispatch).not.toBeCalled()1388 expect((api2 as any).dispatch).not.toBeCalled()1389 expect((api3 as any).dispatch).not.toBeCalled()1390 })13911392 it('dispatches with `api.dispatch` when `api.dispatchFromDevtools` is set to true, connections are isolated from each other', async () => {1393 const options1 = { testConnectionId: 'asdf' }1394 const options2 = { testConnectionId: '2f' }1395 const options3 = { testConnectionId: 'd2e' }1396 const initialState1 = { count: 0 }1397 const initialState2 = { count: 2 }1398 const initialState3 = { count: 5 }1399 const api1 = createStore(1400 devtools(() => initialState1, { enabled: true, ...options1 }),1401 )1402 const api2 = createStore(1403 devtools(() => initialState2, { enabled: true, ...options2 }),1404 )1405 const api3 = createStore(1406 devtools(() => initialState3, { enabled: true, ...options3 }),1407 )1408 ;(api1 as any).dispatch = vi.fn()1409 ;(api1 as any).dispatchFromDevtools = true1410 ;(api2 as any).dispatch = vi.fn()1411 ;(api2 as any).dispatchFromDevtools = true1412 ;(api3 as any).dispatch = vi.fn()1413 ;(api3 as any).dispatchFromDevtools = true1414 const setState1 = vi.spyOn(api1, 'setState')1415 const setState2 = vi.spyOn(api2, 'setState')1416 const setState3 = vi.spyOn(api3, 'setState')14171418 const subscribers = getUnnamedConnectionSubscribers(1419 options1.testConnectionId,1420 options2.testConnectionId,1421 options3.testConnectionId,1422 )1423 const getTestPayload = (n: number) => ({1424 type: 'ACTION',1425 payload: `{ "type": "INCREMENT${n}" }`,1426 })1427 subscribers.forEach((sub, i) => sub(getTestPayload(i + 1)))14281429 expect(api1.getState()).toBe(initialState1)1430 expect(api2.getState()).toBe(initialState2)1431 expect(api3.getState()).toBe(initialState3)1432 expect(setState1).not.toBeCalled()1433 expect(setState2).not.toBeCalled()1434 expect(setState3).not.toBeCalled()1435 expect((api1 as any).dispatch).toHaveBeenLastCalledWith({1436 type: 'INCREMENT1',1437 })1438 expect((api2 as any).dispatch).toHaveBeenLastCalledWith({1439 type: 'INCREMENT2',1440 })1441 expect((api3 as any).dispatch).toHaveBeenLastCalledWith({1442 type: 'INCREMENT3',1443 })1444 })14451446 it('does not throw for unsupported payload, connections are isolated from each other', async () => {1447 const options1 = { testConnectionId: 'asdf' }1448 const options2 = { testConnectionId: '2f' }1449 const options3 = { testConnectionId: 'd2e' }1450 const initialState1 = { count: 0 }1451 const initialState2 = { count: 2 }1452 const initialState3 = { count: 5 }1453 const api1 = createStore(1454 devtools(() => initialState1, { enabled: true, ...options1 }),1455 )1456 const api2 = createStore(1457 devtools(() => initialState2, { enabled: true, ...options2 }),1458 )1459 const api3 = createStore(1460 devtools(() => initialState3, { enabled: true, ...options3 }),1461 )1462 ;(api1 as any).dispatch = vi.fn()1463 ;(api1 as any).dispatchFromDevtools = true1464 ;(api2 as any).dispatch = vi.fn()1465 ;(api2 as any).dispatchFromDevtools = true1466 ;(api3 as any).dispatch = vi.fn()1467 ;(api3 as any).dispatchFromDevtools = true1468 const setState1 = vi.spyOn(api1, 'setState')1469 const setState2 = vi.spyOn(api2, 'setState')1470 const setState3 = vi.spyOn(api3, 'setState')1471 const originalConsoleError = console.error1472 console.error = vi.fn()14731474 const [1475 connectionSubscriber1,1476 connectionSubscriber2,1477 connectionSubscriber3,1478 ] = getUnnamedConnectionSubscribers(1479 options1.testConnectionId,1480 options2.testConnectionId,1481 options3.testConnectionId,1482 )1483 expect(() => {1484 connectionSubscriber1({1485 type: 'ACTION',1486 payload: 'this.increment1()',1487 })1488 }).not.toThrow()1489 expect(console.error).toHaveBeenNthCalledWith(1490 1,1491 '[zustand devtools middleware] Could not parse the received json',1492 (() => {1493 try {1494 JSON.parse('this.increment1()')1495 } catch (e) {1496 return e1497 }1498 })(),1499 )15001501 expect(() => {1502 connectionSubscriber1({1503 type: 'ACTION',1504 payload: 'this.increment2()',1505 })1506 }).not.toThrow()1507 expect(console.error).toHaveBeenNthCalledWith(1508 2,1509 '[zustand devtools middleware] Could not parse the received json',1510 (() => {1511 try {1512 JSON.parse('this.increment2()')1513 } catch (e) {1514 return e1515 }1516 })(),1517 )15181519 expect(() => {1520 connectionSubscriber1({1521 type: 'ACTION',1522 payload: 'this.increment3()',1523 })1524 }).not.toThrow()1525 expect(console.error).toHaveBeenNthCalledWith(1526 3,1527 '[zustand devtools middleware] Could not parse the received json',1528 (() => {1529 try {1530 JSON.parse('this.increment3()')1531 } catch (e) {1532 return e1533 }1534 })(),1535 )15361537 expect(() => {1538 connectionSubscriber1({1539 type: 'ACTION',1540 payload: { name: 'increment', args: [] },1541 })1542 }).not.toThrow()1543 expect(console.error).toHaveBeenNthCalledWith(1544 4,1545 '[zustand devtools middleware] Unsupported action format',1546 )1547 expect(() => {1548 connectionSubscriber2({1549 type: 'ACTION',1550 payload: { name: 'increment', args: [] },1551 })1552 }).not.toThrow()1553 expect(console.error).toHaveBeenNthCalledWith(1554 5,1555 '[zustand devtools middleware] Unsupported action format',1556 )1557 expect(() => {1558 connectionSubscriber3({1559 type: 'ACTION',1560 payload: { name: 'increment', args: [] },1561 })1562 }).not.toThrow()1563 expect(console.error).toHaveBeenNthCalledWith(1564 6,1565 '[zustand devtools middleware] Unsupported action format',1566 )15671568 expect(api1.getState()).toBe(initialState1)1569 expect(api2.getState()).toBe(initialState2)1570 expect(api3.getState()).toBe(initialState3)1571 expect(setState1).not.toBeCalled()1572 expect(setState2).not.toBeCalled()1573 expect(setState3).not.toBeCalled()1574 expect((api1 as any).dispatch).not.toBeCalled()1575 expect((api2 as any).dispatch).not.toBeCalled()1576 expect((api3 as any).dispatch).not.toBeCalled()15771578 console.error = originalConsoleError1579 })1580 })15811582 describe('DISPATCH and payload of type...', () => {1583 it('RESET, it inits with initial state, connections are isolated from each other', async () => {1584 const options1 = { testConnectionId: 'asdf' }1585 const options2 = { testConnectionId: '2f' }1586 const options3 = { testConnectionId: 'd2e' }1587 const initialState1 = { count: 0 }1588 const initialState2 = { count: 2 }1589 const initialState3 = { count: 5 }1590 const api1 = createStore(1591 devtools(() => initialState1, { enabled: true, ...options1 }),1592 )1593 const api2 = createStore(1594 devtools(() => initialState2, { enabled: true, ...options2 }),1595 )1596 const api3 = createStore(1597 devtools(() => initialState3, { enabled: true, ...options3 }),1598 )1599 api1.setState({ count: 1 })1600 api2.setState({ count: 3 })1601 api3.setState({ count: 10 })16021603 const connections = getUnnamedConnectionApis(1604 options1.testConnectionId,1605 options2.testConnectionId,1606 options3.testConnectionId,1607 )1608 const [connection1, connection2, connection3] = connections1609 connections.forEach((conn) => conn.send.mockClear())1610 const subscribers = getUnnamedConnectionSubscribers(1611 options1.testConnectionId,1612 options2.testConnectionId,1613 options3.testConnectionId,1614 )1615 const action = {1616 type: 'DISPATCH',1617 payload: { type: 'RESET' },1618 }1619 subscribers.forEach((sub) => sub(action))16201621 expect(api1.getState()).toStrictEqual(initialState1)fix(tests): change parameters for 'expect' in test (#3483)lstakbefore adoptionc7516c1
lines 1622–1623why, one step back1622 expect(api2.getState()).toStrictEqual(initialState2)1623 expect(api3.getState()).toStrictEqual(initialState3)docs: fix typos (#3042)조우혁before adoption9ba6a63
lines 1624–2628why, one step back1624 expect(connection1.init).toHaveBeenLastCalledWith(initialState1)1625 expect(connection2.init).toHaveBeenLastCalledWith(initialState2)1626 expect(connection3.init).toHaveBeenLastCalledWith(initialState3)1627 connections.forEach((conn) => expect(conn.send).not.toBeCalled())1628 })16291630 it('COMMIT, it inits with current state, connections are isolated from each other', async () => {1631 const options1 = { testConnectionId: 'asdf' }1632 const options2 = { testConnectionId: '2f' }1633 const options3 = { testConnectionId: 'd2e' }1634 const initialState1 = { count: 0 }1635 const initialState2 = { count: 2 }1636 const initialState3 = { count: 5 }1637 const api1 = createStore(1638 devtools(() => initialState1, { enabled: true, ...options1 }),1639 )1640 const api2 = createStore(1641 devtools(() => initialState2, { enabled: true, ...options2 }),1642 )1643 const api3 = createStore(1644 devtools(() => initialState3, { enabled: true, ...options3 }),1645 )1646 api1.setState({ count: 1 })1647 api2.setState({ count: 3 })1648 api3.setState({ count: 10 })1649 const currentState1 = api1.getState()1650 const currentState2 = api2.getState()1651 const currentState3 = api3.getState()16521653 const connections = getUnnamedConnectionApis(1654 options1.testConnectionId,1655 options2.testConnectionId,1656 options3.testConnectionId,1657 )1658 connections.forEach((conn) => conn.send.mockClear())1659 const subscribers = getUnnamedConnectionSubscribers(1660 options1.testConnectionId,1661 options2.testConnectionId,1662 options3.testConnectionId,1663 )1664 const action = {1665 type: 'DISPATCH',1666 payload: { type: 'COMMIT' },1667 }1668 subscribers.forEach((sub) => sub(action))16691670 const [connection1, connection2, connection3] = connections1671 expect(connection1.init).toHaveBeenLastCalledWith(currentState1)1672 expect(connection2.init).toHaveBeenLastCalledWith(currentState2)1673 expect(connection3.init).toHaveBeenLastCalledWith(currentState3)1674 connections.forEach((conn) => expect(conn.send).not.toBeCalled())1675 })1676 })16771678 describe('ROLLBACK...', () => {1679 it('updates state without recording and inits with `message.state, connections are isolated from each other`', async () => {1680 const options1 = { testConnectionId: 'asdf' }1681 const options2 = { testConnectionId: '2f' }1682 const options3 = { testConnectionId: 'd2e' }1683 const initialState1 = { count: 0, increment: () => {} }1684 const initialState2 = { count: 2, increment: () => {} }1685 const initialState3 = { count: 5, increment: () => {} }1686 const api1 = createStore(1687 devtools(() => initialState1, { enabled: true, ...options1 }),1688 )1689 const api2 = createStore(1690 devtools(() => initialState2, { enabled: true, ...options2 }),1691 )1692 const api3 = createStore(1693 devtools(() => initialState3, { enabled: true, ...options3 }),1694 )1695 const newState1 = { foo: 'bar1' }1696 const newState2 = { foo: 'bar2' }1697 const newState3 = { foo: 'bar3' }16981699 const connections = getUnnamedConnectionApis(1700 options1.testConnectionId,1701 options2.testConnectionId,1702 options3.testConnectionId,1703 )1704 connections.forEach((conn) => conn.send.mockClear())1705 const [1706 connectionSubscriber1,1707 connectionSubscriber2,1708 connectionSubscriber3,1709 ] = getUnnamedConnectionSubscribers(1710 options1.testConnectionId,1711 options2.testConnectionId,1712 options3.testConnectionId,1713 )1714 connectionSubscriber1({1715 type: 'DISPATCH',1716 payload: { type: 'ROLLBACK' },1717 state: JSON.stringify(newState1),1718 })1719 connectionSubscriber2({1720 type: 'DISPATCH',1721 payload: { type: 'ROLLBACK' },1722 state: JSON.stringify(newState2),1723 })1724 connectionSubscriber3({1725 type: 'DISPATCH',1726 payload: { type: 'ROLLBACK' },1727 state: JSON.stringify(newState3),1728 })17291730 expect(api1.getState()).toStrictEqual({1731 ...initialState1,1732 ...newState1,1733 })1734 expect(api2.getState()).toStrictEqual({1735 ...initialState2,1736 ...newState2,1737 })1738 expect(api3.getState()).toStrictEqual({1739 ...initialState3,1740 ...newState3,1741 })1742 const [connection1, connection2, connection3] = connections1743 expect(connection1.init).toHaveBeenLastCalledWith({1744 ...initialState1,1745 ...newState1,1746 })1747 expect(connection2.init).toHaveBeenLastCalledWith({1748 ...initialState2,1749 ...newState2,1750 })1751 expect(connection3.init).toHaveBeenLastCalledWith({1752 ...initialState3,1753 ...newState3,1754 })1755 connections.forEach((conn) => expect(conn.send).not.toBeCalled())1756 })17571758 it('does not throw for unparsable `message.state`, connections are isolated from each other', async () => {1759 const increment1 = () => {}1760 const increment2 = () => {}1761 const increment3 = () => {}1762 const options1 = { testConnectionId: 'asdf' }1763 const options2 = { testConnectionId: '2f' }1764 const options3 = { testConnectionId: 'd2e' }1765 const initialState1 = { count: 0, increment: increment1 }1766 const initialState2 = { count: 2, increment: increment2 }1767 const initialState3 = { count: 5, increment: increment3 }1768 const api1 = createStore(1769 devtools(() => initialState1, { enabled: true, ...options1 }),1770 )1771 const api2 = createStore(1772 devtools(() => initialState2, { enabled: true, ...options2 }),1773 )1774 const api3 = createStore(1775 devtools(() => initialState3, { enabled: true, ...options3 }),1776 )1777 const originalConsoleError = console.error1778 console.error = vi.fn()17791780 const connections = getUnnamedConnectionApis(1781 options1.testConnectionId,1782 options2.testConnectionId,1783 options3.testConnectionId,1784 )1785 connections.forEach((conn) => conn.init.mockClear())1786 connections.forEach((conn) => conn.send.mockClear())1787 const [1788 connectionSubscriber1,1789 connectionSubscriber2,1790 connectionSubscriber3,1791 ] = getUnnamedConnectionSubscribers(1792 options1.testConnectionId,1793 options2.testConnectionId,1794 options3.testConnectionId,1795 )1796 connectionSubscriber1({1797 type: 'DISPATCH',1798 payload: { type: 'ROLLBACK' },1799 state: 'foobar',1800 })1801 expect(console.error).toHaveBeenLastCalledWith(1802 '[zustand devtools middleware] Could not parse the received json',1803 (() => {1804 try {1805 JSON.parse('foobar')1806 } catch (e) {1807 return e1808 }1809 })(),1810 )1811 connectionSubscriber2({1812 type: 'DISPATCH',1813 payload: { type: 'ROLLBACK' },1814 state: 'foobar1',1815 })1816 expect(console.error).toHaveBeenLastCalledWith(1817 '[zustand devtools middleware] Could not parse the received json',1818 (() => {1819 try {1820 JSON.parse('foobar1')1821 } catch (e) {1822 return e1823 }1824 })(),1825 )1826 connectionSubscriber3({1827 type: 'DISPATCH',1828 payload: { type: 'ROLLBACK' },1829 state: 'foobar3',1830 })1831 expect(console.error).toHaveBeenLastCalledWith(1832 '[zustand devtools middleware] Could not parse the received json',1833 (() => {1834 try {1835 JSON.parse('foobar3')1836 } catch (e) {1837 return e1838 }1839 })(),1840 )18411842 expect(api1.getState()).toBe(initialState1)1843 expect(api2.getState()).toBe(initialState2)1844 expect(api3.getState()).toBe(initialState3)1845 connections.forEach((conn) => {1846 expect(conn.init).not.toBeCalled()1847 expect(conn.send).not.toBeCalled()1848 })18491850 console.error = originalConsoleError1851 })1852 })18531854 describe('JUMP_TO_STATE...', () => {1855 const increment1 = () => {}1856 const increment2 = () => {}1857 const increment3 = () => {}18581859 it('updates state without recording with `message.state`, connections are isolated from each other', async () => {1860 const options1 = { testConnectionId: 'asdf' }1861 const options2 = { testConnectionId: '2f' }1862 const options3 = { testConnectionId: 'd2e' }1863 const initialState1 = { count: 0, increment: increment1 }1864 const initialState2 = { count: 2, increment: increment2 }1865 const initialState3 = { count: 5, increment: increment3 }1866 const api1 = createStore(1867 devtools(() => initialState1, { enabled: true, ...options1 }),1868 )1869 const api2 = createStore(1870 devtools(() => initialState2, { enabled: true, ...options2 }),1871 )1872 const api3 = createStore(1873 devtools(() => initialState3, { enabled: true, ...options3 }),1874 )1875 const newState1 = { foo: 'bar1' }1876 const newState2 = { foo: 'bar2' }1877 const newState3 = { foo: 'bar3' }18781879 const connections = getUnnamedConnectionApis(1880 options1.testConnectionId,1881 options2.testConnectionId,1882 options3.testConnectionId,1883 )1884 connections.forEach((conn) => conn.send.mockClear())1885 const [1886 connectionSubscriber1,1887 connectionSubscriber2,1888 connectionSubscriber3,1889 ] = getUnnamedConnectionSubscribers(1890 options1.testConnectionId,1891 options2.testConnectionId,1892 options3.testConnectionId,1893 )1894 connectionSubscriber1({1895 type: 'DISPATCH',1896 payload: { type: 'JUMP_TO_STATE' },1897 state: JSON.stringify(newState1),1898 })1899 connectionSubscriber2({1900 type: 'DISPATCH',1901 payload: { type: 'JUMP_TO_STATE' },1902 state: JSON.stringify(newState2),1903 })1904 connectionSubscriber3({1905 type: 'DISPATCH',1906 payload: { type: 'JUMP_TO_STATE' },1907 state: JSON.stringify(newState3),1908 })19091910 expect(api1.getState()).toStrictEqual({1911 ...initialState1,1912 ...newState1,1913 })1914 expect(api2.getState()).toStrictEqual({1915 ...initialState2,1916 ...newState2,1917 })1918 expect(api3.getState()).toStrictEqual({1919 ...initialState3,1920 ...newState3,1921 })1922 connections.forEach((conn) => expect(conn.send).not.toBeCalled())1923 })19241925 it('does not throw for unparsable `message.state`, connections are isolated from each other', async () => {1926 const options1 = { testConnectionId: 'asdf' }1927 const options2 = { testConnectionId: '2f' }1928 const options3 = { testConnectionId: 'd2e' }1929 const initialState1 = { count: 0, increment: increment1 }1930 const initialState2 = { count: 2, increment: increment2 }1931 const initialState3 = { count: 5, increment: increment3 }1932 const api1 = createStore(1933 devtools(() => initialState1, { enabled: true, ...options1 }),1934 )1935 const api2 = createStore(1936 devtools(() => initialState2, { enabled: true, ...options2 }),1937 )1938 const api3 = createStore(1939 devtools(() => initialState3, { enabled: true, ...options3 }),1940 )1941 const originalConsoleError = console.error1942 console.error = vi.fn()19431944 const connections = getUnnamedConnectionApis(1945 options1.testConnectionId,1946 options2.testConnectionId,1947 options3.testConnectionId,1948 )1949 connections.forEach((conn) => conn.send.mockClear())1950 const [1951 connectionSubscriber1,1952 connectionSubscriber2,1953 connectionSubscriber3,1954 ] = getUnnamedConnectionSubscribers(1955 options1.testConnectionId,1956 options2.testConnectionId,1957 options3.testConnectionId,1958 )19591960 connectionSubscriber1({1961 type: 'DISPATCH',1962 payload: { type: 'JUMP_TO_STATE' },1963 state: 'foobar',1964 })1965 expect(console.error).toHaveBeenLastCalledWith(1966 '[zustand devtools middleware] Could not parse the received json',1967 (() => {1968 try {1969 JSON.parse('foobar')1970 } catch (e) {1971 return e1972 }1973 })(),1974 )1975 connectionSubscriber2({1976 type: 'DISPATCH',1977 payload: { type: 'JUMP_TO_STATE' },1978 state: 'foobar2',1979 })1980 expect(console.error).toHaveBeenLastCalledWith(1981 '[zustand devtools middleware] Could not parse the received json',1982 (() => {1983 try {1984 JSON.parse('foobar2')1985 } catch (e) {1986 return e1987 }1988 })(),1989 )1990 connectionSubscriber3({1991 type: 'DISPATCH',1992 payload: { type: 'JUMP_TO_STATE' },1993 state: 'foobar3',1994 })1995 expect(console.error).toHaveBeenLastCalledWith(1996 '[zustand devtools middleware] Could not parse the received json',1997 (() => {1998 try {1999 JSON.parse('foobar3')2000 } catch (e) {The first 2,000 of 2,687 lines.