【问题标题】:How can i test redux .subscribe()我如何测试 redux .subscribe()
【发布时间】:2021-11-05 19:14:53
【问题描述】:

在我想要测试的代码中,有 store.subscribe() 函数,但我不知道如何测试它。

test('should call console.log inside subscribe fn', async () => {
  const store = configureStore(initialState);
  store.subscribe(() => console.log(store.getState())); // console.log was not called

  await wait(100);
})

在我的代码中

// index.ts

export const store = createStore();
store.subscribe(() => console.log(store.getState())); // how can i test it in jest?

【问题讨论】:

    标签: javascript unit-testing redux jestjs


    【解决方案1】:

    你想测试subscriber函数,那么你可以通过dispatch action来触发它。在调度每个动作后断言状态。

    import { configureStore } from '@reduxjs/toolkit';
    
    test('should call console.log inside subscribe fn', async () => {
      expect.assertions(1);
      const store = configureStore({ reducer: (state = 'test state') => state });
      store.subscribe(() => {
        expect(store.getState()).toEqual('test state');
      });
      store.dispatch({ type: '' });
    });
    

    测试结果:

     PASS   redux-toolkit-example  packages/redux-toolkit-example/stackoverflow/69845750/index.test.ts
      ✓ should call console.log inside subscribe fn (4 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        3.869 s
    

    【讨论】:

    • 它可以在测试中工作。但是我该如何测试这个例子呢? ``` const a = () => { store.subscribe(() => console.log(store.getState())) } ``
    • @polRk 使用jest.spyOn(console, 'log')console.log 方法上添加spy,断言它在调度动作后以整个状态调用。
    • 它不工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多