首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为前端组件(react.js)编写Mocha测试规范

为前端组件(react.js)编写Mocha测试规范
EN

Stack Overflow用户
提问于 2017-02-13 08:49:55
回答 1查看 101关注 0票数 0

我在为我的前端组件编写mocha测试规范时遇到了很多麻烦。我的组件看起来非常简单,但对如何编写测试规范一无所知。有没有人能帮我一下?任何帮助都将不胜感激!谢谢

代码语言:javascript
复制
import React from 'react';

//Submit handler takes the message and gives it to the callback of its parent component, ChatApp for rendering and emitting to server
//Keep track of the mssage when you type and assign it to a property (text) in state
class MessageForm extends React.Component {
	constructor(props) {
		super(props)
		this.changeHandler = this.changeHandler.bind(this);
		this.handleSubmit = this.handleSubmit.bind(this);
		this.state = {text: ''}
	}

	handleSubmit(e) {
		e.preventDefault();
		var message = {
			user: this.props.user,
			text: this.state.text,
			language: this.props.language,
			id: 1
		}
		//Connects to ChatApp component
		this.props.onMessageSubmit(message);
		//Set the state of the text to empty string so that next inputted text value can be hanled in the state
		this.setState({ text: '' })
	}

	changeHandler(e) {
		//change the state of text to inputted value
		this.setState({ text: e.target.value });
	}

	render() {
		return (
			<div className="message_form">
				<h3>Write New Message</h3>
				<form onSubmit={this.handleSubmit}>
					<input
						onChange={this.changeHandler}
						value={this.state.text}
						placeholder='Write new message'
					/>
				</form>
			</div>
		)
	}
}

export default MessageForm;

EN

回答 1

Stack Overflow用户

发布于 2017-02-13 16:15:35

使用enzymesinon,您可以执行以下操作:

代码语言:javascript
复制
it("submits message", () => {
    // GIVEN
    const submitCallback = sinon.spy();
    const actualNode = shallow(<MessageForm onMessageSubmit={submitCallback} />);

    // WHEN
    actualNode.find("input").simulate("change", { target: { value: "Test Message" } });
    actualNode.find("form").simulate("submit");

    // THEN
    sinon.assert.calledWith(submitCallback, "Test Message");
});

这只是一个基本的交互性测试。您还可以创建测试来验证HTML呈现和状态转换。查看enzyme文档以获取更多信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42195060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档