File size: 1,827 Bytes
c2b7eb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { ActionCreatorInvariantMiddlewareOptions } from '@internal/actionCreatorInvariantMiddleware'
import { getMessage } from '@internal/actionCreatorInvariantMiddleware'
import { createActionCreatorInvariantMiddleware } from '@internal/actionCreatorInvariantMiddleware'
import type { MiddlewareAPI } from '@reduxjs/toolkit'
import { createAction } from '@reduxjs/toolkit'

describe('createActionCreatorInvariantMiddleware', () => {
  const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})

  afterEach(() => {
    consoleSpy.mockClear()
  })
  afterAll(() => {
    consoleSpy.mockRestore()
  })

  const dummyAction = createAction('aSlice/anAction')

  it('sends the action through the middleware chain', () => {
    const next = vi.fn()
    const dispatch = createActionCreatorInvariantMiddleware()(
      {} as MiddlewareAPI,
    )(next)
    dispatch({ type: 'SOME_ACTION' })

    expect(next).toHaveBeenCalledWith({
      type: 'SOME_ACTION',
    })
  })

  const makeActionTester = (
    options?: ActionCreatorInvariantMiddlewareOptions,
  ) =>
    createActionCreatorInvariantMiddleware(options)({} as MiddlewareAPI)(
      (action) => action,
    )

  it('logs a warning to console if an action creator is mistakenly dispatched', () => {
    const testAction = makeActionTester()

    testAction(dummyAction())

    expect(consoleSpy).not.toHaveBeenCalled()

    testAction(dummyAction)

    expect(consoleSpy).toHaveBeenLastCalledWith(getMessage(dummyAction.type))
  })

  it('allows passing a custom predicate', () => {
    let predicateCalled = false
    const testAction = makeActionTester({
      isActionCreator(action): action is Function {
        predicateCalled = true
        return false
      },
    })
    testAction(dummyAction())
    expect(predicateCalled).toBe(true)
  })
})