我正在尝试测试带有作为道具传递给子组件的参数的函数。我要模拟一个“点击”事件。我不确定我是否做对了。附言:我没有任何错误。这是我下面的内容。
function MovieSummary({movie,addItem}) {
return (
<div key={movie.imdbID} className="movie-container">
<div className="button-container">
<button
id="btn-click"
key={movie.imdbID}
disabled={disabled.indexOf(movie.imdbID) !== -1 || disableButton}
className="btn btn-primary mt-3"
onClick={() => {
addItem({
title: movie.Title,
id: movie.imdbID,
year: movie.Year,
});
handleDisabled(movie.imdbID);
}}
>
Nominate
</button>
</div>
</div>
);
}
export default MovieSummary;
这是我下面的测试内容
it("simulate add movies onclick", () => {
const movie = {
imdbID: 2,
Title: "bola",
Year: 1992,
Poster: "https://media1.giphy.com/media/rwzBCbqt1jqMw/1",
};
const disabled = [2];
const mockFn = jest.fn();
const wrapper = shallow(
<MovieSummary
movie={movie}
disabled={disabled}
addItem={mockFn}
handleDisabled={() => {}}
/>
);
wrapper.find("[id='btn-click']").simulate("click");
expect(mockFn).toHaveBeenCalled();
});
答案 0 :(得分:0)
是的,您做得正确。这是一个完整的单元测试解决方案:
index.jsx
:
import React from 'react';
function MovieSummary({ movie, disabled, addItem, handleDisabled }) {
const disableButton = false;
return (
<div key={movie.imdbID} className="movie-container">
<div className="button-container">
<button
id="btn-click"
key={movie.imdbID}
disabled={disabled.indexOf(movie.imdbID) !== -1 || disableButton}
className="btn btn-primary mt-3"
onClick={() => {
addItem({
title: movie.Title,
id: movie.imdbID,
year: movie.Year,
});
handleDisabled(movie.imdbID);
}}
>
Nominate
</button>
</div>
</div>
);
}
export default MovieSummary;
index.test.jsx
:
import { shallow } from 'enzyme';
import React from 'react';
import MovieSummary from './';
describe('64026812', () => {
it('simulate add movies onclick', () => {
const movie = {
imdbID: 2,
Title: 'bola',
Year: 1992,
Poster: 'https://media1.giphy.com/media/rwzBCbqt1jqMw/1',
};
const disabled = [2];
const mAddItem = jest.fn();
const mHandleDisabled = jest.fn();
const wrapper = shallow(<MovieSummary movie={movie} disabled={disabled} addItem={mAddItem} handleDisabled={mHandleDisabled} />);
const btn = wrapper.find('#btn-click');
btn.simulate('click');
expect(btn.prop('disabled')).toBeTruthy();
expect(mAddItem).toBeCalledWith({ title: 'bola', id: 2, year: 1992 });
expect(mHandleDisabled).toBeCalledWith(2);
});
});
具有覆盖率报告的单元测试结果:
PASS src/stackoverflow/64026812/index.test.tsx (10.143s)
64026812
✓ simulate add movies onclick (14ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 50 | 100 | 100 | |
index.tsx | 100 | 50 | 100 | 100 | 11 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.494s, estimated 12s