简体   繁体   English

如何使用反应测试库测试带有钩子的反应组件

[英]How to test react component with hooks using react testing library

I am trying to test a component which use useTheme hook provided by emotion.js.我正在尝试测试一个使用由emotion.js 提供的useTheme 钩子的组件。 The theme is set during the app initialization.主题是在应用程序初始化期间设置的。

Now when I write my test cases, the useTheme hook is unable to fetch the styles data as only header component is getting mounted for testing.现在,当我编写测试用例时,useTheme 挂钩无法获取 styles 数据,因为只有 header 组件正在安装以进行测试。 How to mock the data provided by hooks.如何模拟钩子提供的数据。

app.js应用程序.js

import { theme } from '../src/utils/styles/themes/default';

const AppRoot = ({ path, Router }) => {
  const routeRenderFunction = (props) => <RouteHandler route={props} />;
  return (
        <ThemeProvider theme={theme}>
          <Router location={path} context={{}}>
            <Switch>
              {routePatterns.map((routePattern) => (
                <Route key={routePattern} path={routePattern} render={routeRenderFunction} />
              ))}
            </Switch>
          </Router>          
        </ThemeProvider>      
  );
};

header.js header.js

import React from "react";
import { css } from "emotion";
import { useTheme } from "emotion-theming";
import * as styles from "./Header.style";

const Header = ({userName = 'Becky Parsons', clinicName = 'The University of Southampton'}) => {
  const theme = useTheme();

  return (
    <div className={css(styles.accountDetails(theme))}>
      <div className={css(styles.accountContainer)}>
        <div className={css(styles.accountSpecifics)}>
          <h5 className={css(styles.accountDetailsH5(theme))} data-testid="user-name">{userName}</h5>
          <h6 className={css(styles.accountDetailsH6(theme))} data-testid="clinic-name">
            {clinicName}
          </h6>
        </div>
        <div className={css(styles.avatar)} />
      </div>
    </div>
  );
};

export default Header;

header.test.js header.test.js

import React from 'react'
import {render} from '@testing-library/react';
import Header from './Header';


test('Check if header component loads', () => {    
    const { getByTestId } = render(<Header userName='Becky Parsons' clinicName='The University of Southampton'/>);
    expect(getByTestId('user-name').textContent).toBe('Becky Parsons');
    expect(getByTestId('clinic-name').textContent).toBe('The University of Southampton');
  })

header.style.js header.style.js

export const accountDetails = theme => ({
  height: '70px',
  backgroundColor: theme.header.backgroundColor,
  textAlign: 'right',
  padding: '10px 40px'
});
export const accountContainer = {
  display: 'flex',
  justifyContent: 'flex-end'
};

Error: Uncaught [TypeError: Cannot read property 'backgroundColor' of undefined]错误:未捕获 [TypeError:无法读取未定义的属性“背景颜色”]

You should wrap your component with ThemeProvider, try this;你应该用 ThemeProvider 包装你的组件,试试这个;

test('Check if header component loads', () => {
  const { getByText } = render(
    <ThemeProvider theme={your theme object...}>
      <Header userName='Becky Parsons' clinicName='The University of Southampton'/>
    </ThemeProvider >
  );

  ...
});

and you can look here: https://github.com/emotion-js/emotion/blob/master/packages/emotion-theming/ tests /use-theme.js你可以看这里: https ://github.com/emotion-js/emotion/blob/master/packages/emotion-theming/tests/use-theme.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用反应测试库测试需要钩子的组件? - How to test Component which requires hook using react testing library? 如何使用 React 测试库测试记忆化组件的回调? - How to test a memoized component's callback using React Testing Library? 无法使用 React 测试库测试包含钩子的 HOC - Unable to test HOC containing hooks using React testing library 使用 test 和 react-testing-library 测试反应组件 - Test a react component using test and react-testing-library 使用 Redux 和 react-testing-library 测试 React 组件 - Test React Component using Redux and react-testing-library 使用 react-hooks-testing-library 在 React Hooks 中模拟 Axios - Mocking Axios in React Hooks using react-hooks-testing-library 如何使用 onClick 函数 Jest/React 测试库测试 React 组件 - How to test react component with onClick function Jest/React testing library 使用 Jest 使用钩子测试 React 功能组件 - Testing React Functional Component with Hooks using Jest 如何使用 React 测试库测试 React 组件是否返回 null 或其子级? - How to test if React component is returning null or its children using React Testing Library? 如何使用反应测试库测试 HOC - How to test HOC using react testing library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM