javascript - ReactJs 测试模拟组件输入和响应,从哪里开始?

标签 javascript unit-testing mocking reactjs

我正在尝试在我的 react 应用程序中测试邮政编码搜索组件。下面是我的组件和点击处理程序,它使用 superagent 从 api 获取数据。我有 karma、jasmine 和 webpack 设置并运行基本组件测试,但如何模拟数据和用户输入?我将所有 json 数据都保存在一个数据文件中。我可以使用 stub 和模拟获得一个简单的示例设置吗?

render: function () {
    return (
        <div className="mainContent add-school-page">
              <Loader loaded={this.state.loaded}>
            <div className="content has-header">
                <div className="list">
                    <label className="item item-input item-stacked-label">
                        <span className="input-label">Postcode</span>
                        <input ref="postcode" type="text" placeholder="A12 3BC"/>
                    </label>
                </div>
                <div className="padding">
                    <button className="button button-block button-positive clickable"
                        onClick={this.searchByPostcode}>
                        Find School
                    </button>
                </div>
                <SearchResults results={this.state.results} />
                <br />
                <br />
            </div>
            </Loader>
        </div>
    );
},

searchByPostcode: function() {
    var postcode = React.findDOMNode(this.refs.postcode).value;
    var url = OsaApiService.buildRequestUrl('find_schools_postcode', [postcode]);
    fetch(url)
        .then(function (response) {
            return response.json();
        }).then(function (json) {
            this.setState({
                results: json.data,
            });
        }.bind(this)).catch(function (ex) {
            console.log(ex);
        });
}

谁能告诉我如何开始?

我尝试过 Jest,但测试需要很长时间才能完成,并且作为一项监视任务,它需要很长时间。

最佳答案

这是一个使用 Sinon.js 的示例测试创建一个假服务器来响应您的请求。它也可以用于 stub 函数,这个测试通过在被测组件上 stub 对 setState 的调用来演示这一点( stub setSate 可能很愚蠢,但我只是想提供一个例子)

var React = require('react/addons'),
    TestUtils = React.addons.TestUtils,
    ComponentUnderTest = require('./component.js'); //whatever component you are testing

describe('ComponentUnderTest', function () {

    it('retrieves data and sets state when button is pressed', function () {
        //setups
        var server = sinon.fakeServer.create();
        server.respondWith('GET', 'find_schools_postcode', 'json_string');
        var component = TestUtils.renderIntoDocument(<ComponentUnderTest />);
        var button = React.findDOMNode(component.refs.button); //you will need to add this ref
        var setStateStub = sinon.stub(component, 'setState'); //you don't have to stub this, you could just check that state was set afterwards

        TestUtils.Simulate.click(button);
        server.respond(); //tells the server to respond

        //expectations
        expect(setStateStub.calledOnce).toBe(true);
        expect(setStateStub.calledWith({results : 'json_string'})).toBe(true);
        //expect(component.state.results).toEqual('json_string'); //if you did not stub setState
    });

});

如果您想在测试套件中使用 Sinon.js,我建议将其包含在您的 Karma 配置文件中:

frameworks: ['jasmine', 'sinon'],

希望这有帮助!

关于javascript - ReactJs 测试模拟组件输入和响应,从哪里开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31315983/

相关文章:

javascript - 这是一个好的 JavaScript 对象模型吗? (电话簿项目)

javascript - 如何按属性值创建组检查元素

javascript - 无法使用 Backbone.history.start() 和 QUnit 调用未定义错误的方法 'start'

android - 通过伪造 NFC 标签扫描来测试应用程序

c# - 我可以创建一个符合接口(interface)并且也知道其基类上的方法的模拟吗?

c# - 模拟 System.Net.FtpClient GetHash 方法

javascript - Jquery 变量.addClass()

javascript - 如何为 php 语法指定样式

javascript - 如何在 jasmine 中抽象和重用 describe() block ?

javascript - 如何使用 Jest 和 Enzyme 测试 getDerivedStateFromProps