开发者问题收集

在测试组件时,如何为 React 中的状态分配值?

2021-11-15
1959

我正在使用 useContext 在 React 应用程序中传递状态,我是测试新手,我正在尝试对名为 timer.js 的 React 组件进行单元测试(Jest/Enzyme)

import React, { useEffect, useContext } from 'react';
import { GameContext } from './global/contexts';


export default function Timer(){
const {timer, setTimer} = useContext(GameContext);
useEffect(()=>{
    if (timer === 0) {
         return;
    }  
    const interval = setInterval(()=>{
        setTimer((prev)=> prev-1);
    },10);
    return () => clearInterval(interval);
})

return (
    <p data-testid="timer">Timer : {Math.floor(timer/100)}</p>
)};

我想为该组件编写测试,但收到错误消息:

const wrapper = shallow(<Timer/>);

TypeError: Cannot destructure property 'timer' of '(0 , _react.useContext)(...)' as it is undefined.

1个回答

使用 React Testing Library,您可以执行类似这样的操作来设置可重复使用的测试组件。这是我如何实现这一点的一个非常粗略的示例,但是...

import React from 'react';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import MyContextProvider from './MyContextProvider';
import MyComponent from './MyComponent';

const Render = (args) => {
  return (
    <MyContextProvider {...args}>
      <MyComponent />
    </MyContextProvider>
  );
};

async function renderTest(args) {
  render(<Render {...args} />);

  const firstField = await screen.findByLabelText('Foo');
  const submit = await screen.findByText('Submit Button');
  return {
    firstField,
    submit
  };
};

describe('MyComponent', function () {
  it ('should fire some change', async function() {
    const {firstField, submit} = await renderTest({val1: 'bar'});
    fireEvent.change(firstField, {target: {value: 'blah'}});
    await waitFor(() => expect(submit).toBeEnabled());
    fireEvent.click(submit);
    await waitFor(() => expect(screen.findByText('They chose blah').toBeInTheDocument());
  });
});
Steve -Cutter- Blades
2021-11-15