繁体   English   中英

我如何测试 redux .subscribe()

[英]How can i test redux .subscribe()

在我要测试的代码中,有 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);
})

您想测试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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM