我正在尝试测试一个带有参数的函数,该参数被作为道具传递给子组件。我想在它上面模拟一个"click“事件。我不确定我这样做的方式是否正确。附言:我没有得到任何错误。这是我下面的组件。
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();
});发布于 2020-09-29 13:54:51
是的,你做得很对。下面是一个完整的单元测试解决方案:
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 12shttps://stackoverflow.com/questions/64026812
复制相似问题