gpt4 book ai didi

javascript - 在父组件中测试子组件的按钮

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

我是测试新手,三天以来一直在搜索如何解决我的问题。希望你能帮助我..我有一个父组件:

import React from 'react';
import './Subscribe.scss';
import Button from '../../Components/Button/Button';

class Subscribe extends React.Component {
state = {
user: {
firstName: '',
pseudo:'',
email: '',
password:''
}
}

handleChange = (e) => {
this.setState({
user: {...this.state.user, [e.target.name]: e.target.value}
}, () => console.log(this.state))
}

onSubmit = (e) => {
// e.preventDefault()
console.log("you've clicked")
//todo
}
render() {
return(
<form className='subscribe' id='subscriptionForm'>
<label htmlFor='firstName'>Prénom :</label>
<input
data-testid='inputString'
type='text'
name='firstName'
onChange={this.handleChange}
value={this.state.user.firstName}
/>

<label htmlFor='pseudo'>Pseudo :</label>
<input
data-testid='inputString'
type='text'
name='pseudo'
onChange={this.handleChange}
value={this.state.user.pseudo}
/>
<label htmlFor='email'>Email :</label>
<input
data-testid='inputString'
type='email'
name='email'
onChange={this.handleChange}
value={this.state.user.email}
/>
<label htmlFor='password'>
password :
</label>
<Button id='submitSubscription' text='Go go !' onSubmit={this.onSubmit}/>
<Button text='Annuler'/>
</form>
)
}
}

export default Subscribe;

子组件:

import React from "react";

const Button = (props) => {
return (
<button type="button" onClick={props.onClick}>{props.text}</button>
)
}
Button.displayName = 'Button'
export default Button

我想测试一下,但没有任何效果...

我的测试:


import React from 'react';
import { shallow, mount } from 'enzyme';
import Subscribe from './Subscribe.js';
import Button from "./../../Components/Button/button.js"


describe('<LogIn />', () => {
it('Should call onSubmit on subscribe component when button component is clicked and allow user to subscribe ', () => {
// Rend le composant et les enfants et renvoie un wrapper Enzyme
const wrapper = mount(<Subscribe />);
// Trouve la première balise bouton
const button = wrapper.find("#submitSubscription");
// Récupère l'instance React du composant
const instance = wrapper.instance();
// Ecoute les appels à la fonction on Submit
jest.spyOn(instance, "onSubmit");
button.simulate('click');
expect(instance.onSubmit).toHaveBeenCalled();
})

评论是我尝试过的。答案仍然是预期调用数:>= 1 已接调用数:0我也愿意尝试 react 测试,所以我很乐意提供任何帮助。

提前致谢!

最佳答案

您的表单设置有一些错误。主要是,您需要在 formonSubmit 属性上放置一个 handleSubmit 并将其中一个按钮更改为具有 submit 的 type 属性。请参阅代码和框以获取工作版本:

工作示例(您可以通过单击浏览器选项卡旁边的测试选项卡来运行测试):

Edit Simple Form Testing

这个例子使用了一些 es6 syntax ,如果您不熟悉,请阅读以下内容:

<小时/>

组件/按钮/Button.js

import React from "react";

const Button = props => (
<button
style={{ marginRight: 10 }}
type={props.type || "button"}
onClick={props.onClick}
>
{props.text}
</button>
);

Button.displayName = "Button";

export default Button;

组件/订阅/Subscribe.js

import React, { Component } from "react";
import Button from "../Button/Button";
// import './Subscribe.scss';

const initialState = {
user: {
firstName: "",
pseudo: "",
email: "",
password: ""
}
};

class Subscribe extends Component {
state = initialState;

handleChange = ({ target: { name, value } }) => {
// when spreading out previous state, use a callback function
// as the first parameter to setState
// this ensures state is in sync since setState is an asynchronous function
this.setState(
prevState => ({
...prevState,
user: { ...prevState.user, [name]: value }
}),
() => console.log(this.state)
);
};

handleCancel = () => {
this.setState(initialState);
};

handleSubmit = e => {
e.preventDefault();
this.props.onSubmit(this.state);
};

render = () => (
<form
onSubmit={this.handleSubmit}
className="subscribe"
id="subscriptionForm"
>
<label htmlFor="firstName">Prénom :</label>
<input
data-testid="inputString"
type="text"
name="firstName"
onChange={this.handleChange}
value={this.state.user.firstName}
/>
<br />
<label htmlFor="pseudo">Pseudo :</label>
<input
data-testid="inputString"
type="text"
name="pseudo"
onChange={this.handleChange}
value={this.state.user.pseudo}
/>
<br />
<label htmlFor="email">Email :</label>
<input
data-testid="inputString"
type="email"
name="email"
onChange={this.handleChange}
value={this.state.user.email}
/>
<br />
<label htmlFor="password">password :</label>
<input
data-testid="inputString"
type="password"
name="password"
onChange={this.handleChange}
value={this.state.user.password}
/>
<br />
<br />
<Button type="button" text="Annuler" onClick={this.handleCancel} />
<Button id="submitSubscription" type="submit" text="Soumettre" />
</form>
);
}

export default Subscribe;

components/Subscribe/__tests__/Subscribe.test.js (我传入一个 onSubmit 属性来模拟它,我希望它被调用。这是与针对 React 的事件回调实现进行测试相比,这是一个更常见的测试用例,这会迫使您不必要地监视类字段。通过针对 prop (或状态更改或某些辅助操作)进行测试,我们已经涵盖了是否或者回调不起作用!)

import React from "react";
import { mount } from "enzyme";
import Subscribe from "../Subscribe.js";

const onSubmit = jest.fn();

const initProps = {
onSubmit
};

describe("<LogIn />", () => {
it("Should call onSubmit on subscribe component when button component is clicked and allow user to subscribe ", () => {
const wrapper = mount(<Subscribe {...initProps} />);
const spy = jest.spyOn(wrapper.instance(), "handleSubmit"); // not necessary
wrapper.instance().forceUpdate(); // not necessary

wrapper.find("button[type='submit']").simulate("submit");

// alternatively, you could simply use:
// wrapper.find("form").simulate("submit");

expect(spy).toHaveBeenCalledTimes(1); // not necessary
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});

index.js

import React from "react";
import { render } from "react-dom";
import Subscribe from "./components/Subscribe/Subscribe";
import "./styles.css";

const onSubmit = formProps => alert(JSON.stringify(formProps, null, 4));

render(
<Subscribe onSubmit={onSubmit} />,
document.getElementById("root")
);

关于javascript - 在父组件中测试子组件的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130603/

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