React/Jest:测试React上下文方法(结果:TypeError:SetScore不是函数)

发布于 2025-02-01 11:40:45 字数 2103 浏览 2 评论 0原文

我正在使用React Context API创建游戏。

在我的一个组件(gamestatus)中,我从提供商那里汲取了一些方法:

const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;

在组件中,我调用了开始游戏按钮的这三种方法,这又将状态放回了提供者中。

然后, Gamestatus组件

import React from 'react';
import { MyContext } from './Provider';

const GameStatus = ({ gameStart, gameEnd, score, total, getPlayers }: { gameStart: boolean, gameEnd: boolean, getPlayers: () => void, score: number, total: number }) => {
    const context = React.useContext(MyContext);
    const { setGameStart, setGameEnd, setScore } = context;
    return (
        <>
            {!gameStart && (
                <button onClick={() => {
                    getPlayers();
                    setScore(0);
                    setGameStart(true);
                    setGameEnd(false);
                }}>
                    Start game
                </button>
            )}
            {gameEnd && (
                <p>Game end - You scored {score} out {total}</p>
            )}
        </>
    )
}

export default GameStatus;

然后在下面的测试文件中我要测试,当单击“开始游戏”按钮时,启动了游戏(检查DOM已删除了按钮,现在正在显示游戏)。

但是我不确定如何将方法拉到测试文件时:

结果:typeError:setScore不是函数

我尝试仅复制:

const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;

但是我得到了一个无效的挂钩调用因为我无法在测试中使用React钩子。

有什么想法吗?还是更好的测试方法?谢谢

Gamestatus测试

import React from 'react';
import { shallow } from 'enzyme';
import { MyContext } from '../components/Provider';
import GameStatus from '../components/GameStatus';

test('should start the game', () => {
    const getPlayers = jest.fn();

    const uut = shallow(
        <MyContext.Provider>
            <GameStatus
                getPlayers={getPlayers}
            />
        </MyContext.Provider>
    ).dive().find('button');

    uut.simulate('click');

    console.log(uut.debug());
});

I'm using React Context API to create a game.

In one of my components (GameStatus) I pull in some methods from the provider:

const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;

And in the component I invoke these three methods onClick of the start game button, which in turn sets the state back in the provider.

GameStatus Component

import React from 'react';
import { MyContext } from './Provider';

const GameStatus = ({ gameStart, gameEnd, score, total, getPlayers }: { gameStart: boolean, gameEnd: boolean, getPlayers: () => void, score: number, total: number }) => {
    const context = React.useContext(MyContext);
    const { setGameStart, setGameEnd, setScore } = context;
    return (
        <>
            {!gameStart && (
                <button onClick={() => {
                    getPlayers();
                    setScore(0);
                    setGameStart(true);
                    setGameEnd(false);
                }}>
                    Start game
                </button>
            )}
            {gameEnd && (
                <p>Game end - You scored {score} out {total}</p>
            )}
        </>
    )
}

export default GameStatus;

Then in my test file below I want to test that when the start game button is clicked the game is started (check the DOM has removed the button and is now showing the game).

But I'm not sure how to pull in the methods in to the test file as I get:

Result: TypeError: setScore is not a function

I tried just copying:

const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;

But then I get an invalid hook call as I can't use React hooks inside the test.

Any ideas? Or a better approach to testing this? Thanks

GameStatus Test

import React from 'react';
import { shallow } from 'enzyme';
import { MyContext } from '../components/Provider';
import GameStatus from '../components/GameStatus';

test('should start the game', () => {
    const getPlayers = jest.fn();

    const uut = shallow(
        <MyContext.Provider>
            <GameStatus
                getPlayers={getPlayers}
            />
        </MyContext.Provider>
    ).dive().find('button');

    uut.simulate('click');

    console.log(uut.debug());
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

把梦留给海 2025-02-08 11:40:45

我不确定这是否有帮助,但是由于您的第一种方法是在测试中使用钩子,因此您可以尝试使用库来渲染钩子。我不熟悉酶,但我使用 react hook hooks testing库为了使我的我在我的测试中挂钩。
您可以这样使用:

let testYourHook= renderHook(yourHook);

testyourhook值不是动态的,因此您必须每次获得值:

testYourHook.result.current

I'm not sure if this helps but since your first approach was to use hooks inside your test you could try to use a library for rendering hooks. I'm not familiar with enzyme but I used React Hooks Testing Library in order to render my hooks inside my tests.
You can use it like that:

let testYourHook= renderHook(yourHook);

testYourHook value is not dynamic, so you have to get the value everytime with:

testYourHook.result.current
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文