【问题标题】:Testing a React component - determining where the functionality should be tested测试 React 组件 - 确定应该在哪里测试功能
【发布时间】:2015-10-21 14:03:39
【问题描述】:

我对一般测试非常陌生,而不仅仅是 React 测试,所以我仍然试图弄清楚如何 测试,以及 什么 测试.

这是我在提交表单时调用的 login 回调:

login() {
    let typedUsername = React.findDOMNode(this.refs.username).value;
    if (!typedUsername) {
        return this.setState({
            errored: true
        });
    }
    // we don't actually send the request from here, but set the username on the AuthModel and call the `login` method below
    AuthModel.set('username', typedUsername);
    AuthModel.login();
},

AuthModel 是一个 Backbone.js 模型。但是对于这个问题,可以说它是一个外部模块,我要导入到我的Login.jsx 组件中。

我正在编写一个测试,看看如果输入了用户名,那么AuthModel.login() 会被调用。我想在我的test.Login.js 测试文件中测试它,我是否要在我的test.AuthModel.js 测试文件中测试它?

it('calls login when there\'s a username present', () => {
    React.findDOMNode(LoginElement.refs.username).value = 'foo';
    TestUtils.Simulate.submit(form);
    // not sure which direction to take this test
});

当前测试(test.login.js)的上下文...

感谢任何建议,正如我所说,这确实是我做过的第一次测试。

【问题讨论】:

    标签: javascript unit-testing backbone.js jasmine reactjs


    【解决方案1】:

    听起来你想要一个间谍。这将删除 AuthModel 的真正实现,并将其替换为您可以预期的对象:

    spyOn(AuthModel, 'login');
    // trigger login somehow
    expect(AuthModel.login).toHaveBeenCalled();
    

    或者如果您还想测试传递的参数:

    expect(AuthModel.login).toHaveBeenCalledWith('username', 's3cretpassw0rd);
    

    【讨论】:

    • 王牌,谢谢。我相信我最终得到了类似的结果:gist.github.com/benhowdle89/3e1cfd863e5e920b79ae 我的问题是从测试中到达AuthModel,因为它被导入到Login.jsx 组件中。你会说我的方法看起来相当合理吗?
    猜你喜欢
    • 1970-01-01
    • 2014-02-04
    • 2019-08-06
    • 2023-04-09
    • 2023-03-13
    • 2021-08-18
    • 2021-09-04
    • 2010-10-23
    • 2021-08-30
    相关资源
    最近更新 更多