In my code, that i want to test, has store.subscribe() function, and i dont know, how can i test it.
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);
})
And in my code
// index.ts
export const store = createStore();
store.subscribe(() => console.log(store.getState())); // how can i test it in jest?
You want to test the subscriber function, then you can trigger it through dispatch action. Assert the state after each action is dispatched.
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: '' });
});
test result:
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