模拟 store.getState()

Posted

技术标签:

【中文标题】模拟 store.getState()【英文标题】:mocking store.getState() 【发布时间】:2019-10-17 08:39:42 【问题描述】:

我想断言,当一个函数使用 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();
);

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

【参考方案2】:
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();
);

【讨论】:

以上是关于模拟 store.getState()的主要内容,如果未能解决你的问题,请参考以下文章

store.getState 不是一个函数 Redux-persist

无需订阅即可读取 React Context 值,例如 Redux 的 store.getState()

REDUX:通过 this.props 访问的存储变量已过时,但 store.getState() 有效

TypeError: _this.store.getState is not a function when using connect from Redux

Redux学习笔记

Redux学习笔记