在react-testing-library中测试div或ap标签中的文本的最佳方法是什么?
让我们假设我们有一个这样的 React 组件:
const Greeting = ({name}) => {
return <div>Welcome {name}!</div>
}
Run Code Online (Sandbox Code Playgroud)
测试组件呈现预期值的最佳方法是什么,是使用toBeInTheDocument():
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument()
})
Run Code Online (Sandbox Code Playgroud)
或使用toBeVisible()
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeVisible()
})
Run Code Online (Sandbox Code Playgroud)
或两者都不是:
import {render, screen} from …Run Code Online (Sandbox Code Playgroud) 我想将 Emotion 与 CRA 一起使用,因此我按照文档安装了它,并尝试使用 css prop,如下例所示:
import { FC } from "react";
import { TypographyProps } from "./Typography.propTypes";
import * as styles from "./Typography.styles";
export const Typography: FC<TypographyProps> = ({
children,
}) => {
return <h1 css={styles.typography}>{children}</h1>;
};
Run Code Online (Sandbox Code Playgroud)
但没有成功。
通过检查代码,我发现了这一点:
<h1 css="You have tried to stringify object returned from `css` function.
It isn't supposed to be used directly (e.g. as value of the `className` prop),
but rather handed to emotion so it can handle it (e.g. as value of …Run Code Online (Sandbox Code Playgroud)