gpt4 book ai didi

reactjs - 如何在过滤对象数组的 React 中测试(单元测试)reducer

转载 作者:行者123 更新时间:2023-11-28 21:06:47 25 4
gpt4 key购买 nike

我有一个问题无法为我的一个 reducer 编写正确的测试。

我的 reducer 外观:

export const initialState = {
time: undefined,
products: undefined,
filteredProducts: [],
search: ""
};

case "FILTER_BY_VALUE": {
return {
...state,
search: payload,
filteredProducts: [
...state.products.filter(product =>
product.name.toLowerCase().startsWith(payload.toLowerCase())
)
]
};
}

我的 reducer 按值过滤对象数组(在我的示例中它是有效负载)

我的测试外观:

it("FILTER_BY_VALUE", () => {
const action = {
type: "FILTER_BY_VALUE",
payload: "dsf"
};
expect(data(initialState, action)).toEqual({
...initialState,
search: action.payload
// filteredProducts: Object
});
});

错误在图像中: enter image description here

最佳答案

确保 data 中传递的 initialState 有一个 products 字段。

products 从它的使用方式来看似乎是一个数组,并且包含具有 name 字段的对象。


it("FILTER_BY_VALUE", () => {
const initialState = {
products: [{name: 'dsffoo'}, {name: 'bardsf'}]
}

const action = {
type: "FILTER_BY_VALUE",
payload: "dsf"
};

expect(data(initialState, action)).toEqual({
...initialState,
search: action.payload,
filteredProducts: ['dsffoo']
});
});

关于reactjs - 如何在过滤对象数组的 React 中测试(单元测试)reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939644/

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