如何使用React测试库使用钩子测试React组件

我正在尝试测试使用由motion.js提供的useTheme挂钩的组件。在应用初始化期间设置了主题。

现在,当我编写测试用例时,useTheme钩子无法获取样式数据,因为仅安装了标题组件进行测试。如何模拟钩子提供的数据。

app.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

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

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

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

错误:未捕获[TypeError:无法读取未定义的属性'backgroundColor']

gordon000 回答:如何使用React测试库使用钩子测试React组件

您应该使用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 >
  );

  ...
});

,您可以在这里查看:https://github.com/emotion-js/emotion/blob/master/packages/emotion-theming/tests/use-theme.js

本文链接:https://www.f2er.com/3147396.html

大家都在问