如何用Jest编写useSelector的测试



我是测试新手,非常困惑我需要做些什么来彻底测试我的MealsSummary.tsx组件。我想从测试我的组件是否正确地从reduxstore检索items开始。我从SO找到了几个答案来设置我的模拟函数,尽管我不确定设置是否正确。如果是,在测试"useSelector"模拟函数方面,我下一步应该做什么?

MealsSummary.test.tsx

describe('mock ', () => {
jest.mock("react-redux", () =>({ 
...jest.requireActual("react-redux"),
useSelector: jest.fn()
}))
describe("testing useselector", () => {
const mockedState = {
user: {
image: 'null',
name: 'testing', 
id: 'name+date',
calories: 2000,
proteins: 150,
carbohydrates: 200, 
fats: 90, 
},
};
test('get items', () =>{
//not sure what to write
})
});
})

MealsSummary.tsx

import { useSelector } from "react-redux"
import { RootState } from "../../redux/store";
import { ScrollView, StyleSheet, Text} from "react-native"
import { MealCard } from './MealCard'
export const MealsSummary = (): JSX.Element => {
const { items } = useSelector((store: RootState) => store.nutrition)
let title: string = 'Food'
return (<>
<Text style={styles.title}>{title}</Text>
<ScrollView >
{items.map(item => (
<MealCard item={item} key={item.id}/>
))}
</ScrollView>
</>)
}

Donotmockreact-redux包的useSelector,将破坏其功能。相反,我们应该使用reduxcreateStoreAPI创建一个存储,并将该存储传递给Provider组件。我们可以在创建redux存储时创建模拟状态。

import { render } from "@testing-library/react";
import React from "react";
import { Provider, useSelector } from "react-redux"
import { createStore } from "redux";
type RootState = {
nutrition: {
items: any[]
}
};
export const MealsSummary = (): JSX.Element => {
const { items } = useSelector((store: RootState) => store.nutrition);
console.log('items: ', items);
return <div />
}
describe("74765250", () => {
test('should pass', () => {
const store = createStore((state = { nutrition: { items: [1, 2, 3] } }) => state)
render(<Provider store={store}><MealsSummary /></Provider>)
})
})

测试结果:

PASS  stackoverflow/74765250/index.test.tsx (13.661 s)
74765250
✓ should pass (36 ms)
console.log
items:  [ 1, 2, 3 ]
at MealsSummary (stackoverflow/74765250/index.test.tsx:13:11)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        17.37 s
Ran all test suites related to changed files.

更多测试用例,见useSelector.spec.tsx文件

相关内容

  • 没有找到相关文章

最新更新