gpt4 book ai didi

javascript - 模拟 store.getState()

转载 作者:行者123 更新时间:2023-11-30 14:00:28 26 4
gpt4 key购买 nike

我想断言,当函数使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com