【问题标题】:mocking store.getState()模拟 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();
});

【问题讨论】:

    标签: javascript redux jestjs


    【解决方案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();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        • 2019-02-12
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多