我无法在我的玩笑测试中获得测试 ID。我是反应测试的新手。我想测试这个组件并返回例如之前给出的 h3 文本。
告诉我:
“TestingLibraryElementError:无法通过以下方式找到元素:[data-testid="testH3"]”
你能帮我吗?
// Component
import React from 'react';
import './Card.scss';
import Card from '@material-ui/core/Card';
import { Link } from "react-router-dom";
function MovieCard({title, image}) {
return (
<div className="card__container">
<Link to={"/details/" + title}>
<Card className="card">
<img src={image} alt=""/>
<div className="card__info">
<h3
data-testid="testH3"
className="card__title">{ title }
</h3>
</div>
</Card>
</Link>
</div>
)
}
export default MovieCard
// test
import React from 'react';
import { render, screen, cleanup } from '@testing-library/react';
import MovieCard from '../MovieCard';
import { BrowserRouter as Router } from "react-router-dom";
afterEach(cleanup);
describe('Test MovieCard', () => {
const tree = render(
<Router>
<MovieCard title="Batman" image="imagesrc"/>
</Router>
)
it('should match with snapshot', () => {
screen.debug();
expect(tree).toMatchSnapshot();
});
it('test h3', () => {
const {getByTestId} = tree;
const element = screen.getByTestId('testH3')
});
});
更新:
最终代码现在运行良好。谢谢各位
import React from 'react';
import { render, screen, cleanup } from '@testing-library/react';
import MovieCard from '../MovieCard';
import { BrowserRouter as Router } from "react-router-dom";
afterEach(cleanup);
describe('Test MovieCard', () => {
function tree() {
return render(
<Router>
<MovieCard title="Batman" image="imagesrc"/>
</Router>
)
}
it('should match with snapshot', () => {
expect(tree()).toMatchSnapshot();
});
it('test h3 text is Batman', () => {
const {getByTestId} = tree();
const element = screen.getByTestId('testH3')
expect(element.textContent).toEqual("Batman")
screen.debug();
});
});
答案 0 :(得分:0)
使用 function
而不是 const
describe('Test MovieCard', () => {
function tree() {
return render(
<Router>
<MovieCard title="Batman" image="imagesrc"/>
</Router>
)
}
it('should match with snapshot', () => {
screen.debug();
expect(tree()).toMatchSnapshot();
});
it('test h3', () => {
const {getByTestId} = tree();
const element = screen.getByTestId('testH3')
});
});