redux 如何使用Jest编写useSelector测试

mwg9r5ms  于 2022-12-13  发布在  Jest
关注(0)|答案(1)|浏览(207)

我是测试新手,对于我需要做什么来彻底测试我的MealsSummary.tsx组件感到非常困惑。我想从测试我的组件是否正确地从redux store中检索items开始。我从SO那里找到了一些答案来设置我的mock函数,尽管我不确定设置是否正确。如果正确,在测试我的“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>
    </>)
}
1szpjjfi

1szpjjfi1#

不要模拟react-redux包的useSelector,这样会破坏它的功能。相反,我们应该使用reduxcreateStore API创建一个存储,并将该存储传递给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文件

相关问题