gpt4 book ai didi

javascript - 如何在 Enzyme React 中模拟按钮单击?

转载 作者:行者123 更新时间:2023-11-28 03:37:52 24 4
gpt4 key购买 nike

模拟按钮单击似乎是一个非常简单/标准的操作。但是,我无法让它在 reacyt Jest.js 测试中工作。

下面是我尝试过的,错误消息是什么以及我想测试的代码

我想测试的代码

class Home extends React.Component {

constructor(props) {
super(props)

this.state = {
showAssessment: false
};
}
assessment = (boolean) => {
this.setState({
showAssessment: boolean
})
}

render() {
if (this.state.showAssessment === true) {
return <App
assessment = {
this.assessment
}
/>
} else {
return ( < div className='container-fluid' style={landingPage}>
<
Component1 / >
<
button className='btn btn-dark' style={matchToolButton} onClick = {
() => this.assessment(true)
} > Match Tool < /button> < /
div > )
}
}

}

我编写的测试:

import React from 'react';

import { shallow, mount, render } from 'enzyme';

import Home from './Home';


test ('Home Button', () => {
it ('It calls assessment function when clicked', () => {


const wrapper = mount(<Home/>); // rednoing the home componenet/ testing
wrapper.instance().assessment = jest.fn(); //if this isn't working try wrapper.instance().assessment

wrapper.find('button').simulate('click');
expect(wrapper.assessment).toHaveBeenCalled();// see comment on line 14 keep the same

});

});


我收到的错误消息


FAIL src/Home.test.js
● Test suite failed to run

/Users/mbyousaf/Desktop/Bucket/dsp_poc2_uwe/front-end/src/Home.test.js: Unexpected token (12:30)
10 |
11 |
> 12 | const wrapper = mount(<Home/>); // rednoing the home componenet/ testing
| ^
13 | wrapper.instance().assessment = jest.fn(); //if this isn't working try wrapper.instance().assessment
14 |
15 | wrapper.find('button').simulate('click');

最佳答案

首先你的测试中有 test(... it(... 。它无法运行。它应该是描述(... it(...

其次,React 测试库使您想要实现的目标变得非常容易(取代 enzyme ):

react-testing-library

import { render, fireEvent } from "@testing-library/react";

describe('Home Button', () => {
it ('It calls assessment function when clicked', () => {
const { getByText } = render(<Home/>);
fireEvent.click(getByText("Match Tool"));
// test now whatever should be differnt after the button is clicked
...

关于javascript - 如何在 Enzyme React 中模拟按钮单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57553857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com