redux 模拟存储.getState()

nbewdwxp  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(146)

我想Assert当一个函数使用store.getState()得到redux状态值时,它会根据状态条件做各种事情。我如何能够Assert/模拟我想要的状态值,以用于使用store.getState()方法的某些测试?谢谢。

示例函数.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;

示例函数.测试.js:

import sampleFunction from './sampleFunction.js';

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

cqoc49vn1#

你能做的就是嘲笑你的商店

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();
});
kknvjkwl

kknvjkwl2#

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();
});

相关问题