简体   繁体   中英

mocking store.getState()

I want to assert that when a function gets my redux state value using store.getState() , it does various things based on the conditions of that state. How am I able to assert / mock what I want the state value to be for certain tests using the store.getState() method? Thanks.

sampleFunction.js:

import { store } from './reduxStore';

const sampleFunction = () => {
  const state = store.getState();
  let result = false;
  if (state.foo.isGood) {
    result = true;
  }

  return result;
};

export default sampleFunction;

sampleFunction.test.js:

import sampleFunction from './sampleFunction.js';

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});

What you can do to mock your store is

import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';

jest.mock('./reduxStore')

const mockState = {
  foo: { isGood: true }
}

// in this point store.getState is going to be mocked
store.getState = () => mockState

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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