javascript - 模拟 store.getState()

标签 javascript redux jestjs

我想断言,当函数使用 store.getState() 获取我的 redux 状态值时,它会根据该状态的条件执行各种操作。对于使用 store.getState() 方法的某些测试,我如何断言/模拟我想要的状态值?谢谢。

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

最佳答案

你可以做些什么来模拟你的商店

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

关于javascript - 模拟 store.getState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56399446/

相关文章:

javascript - Angular - 在 ng-repeat 内添加赞成按钮

JavaScript 多种返回类型

reactjs - 如何在 React 组件中测试 Redux 的 dispatch() 是否被调用(Jest + Enzyme)

javascript - "Navbar refers to a value, but is being used as a type here"在测试时尝试呈现我的组件的浅拷贝

javascript - 数据表选定行背景颜色

javascript - 如何克隆 div 中的所有内容而不克隆外部 div?

javascript - 使用 Jest 测试窗口重新加载 Redux reducer

javascript - React-Redux : Infinite loop when concat to an array in state?

reactjs - 如何使用Redux在Meteor App中加载数据?

typescript - 如何使用 jest 测试 Apollo Server 订阅?