Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 545
Jimmy Avatar asked May 31 '19 17:05

Jimmy


People also ask

What is mock store?

A mock store for testing Redux async action creators and middleware. The mock store will create an array of dispatched actions which serve as an action log for tests. Please note that this library is designed to test the action-related logic, not the reducer-related one.

How to test Redux application?

Redux can be tested with any test runner, since it's just plain JavaScript. One common option is Jest, a widely used test runner that comes with Create-React-App, and is used by the Redux library repos. If you're using Vite to build your project, you may be using Vitest as your test runner.

What is mocking in JavaScript?

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.


2 Answers

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();
});
like image 69
Arnold Gandarillas Avatar answered Sep 18 '22 11:09

Arnold Gandarillas


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


beforeAll(() => {
jest.mock('./reduxStore')

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

 // making getState as mock function and returning mock value
 store.getState = jest.fn().mockReturnValue(mockState)

});

afterAll(() => {
 jest.clearAllMocks();
 jest.resetAllMocks();
});

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});
like image 42
Avinash Avatar answered Sep 17 '22 11:09

Avinash