React-Redux Connected Component测试正确的操作已在click事件上发送

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React-Redux Connected Component测试正确的操作已在click事件上发送相关的知识,希望对你有一定的参考价值。

我是使用jest和酶测试react-redux组分的新手,到目前为止,我发现这是一个挑战。

我有一个登录页面,如果在单击登录按钮后登录失败,我想测试正确的错误操作是否已发送。

这就是我测试连接组件的方式,

require('../jsDomSetup');
import React from 'react';
import { Provider } from 'react-redux';
import loginDefault, {Login}  from '../../app/routes/Login/LoginContainer';
import {mount, shallow} from 'enzyme';
import loginActions from '../../app/redux/actions/loginActions';
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
import nock from 'nock';

describe("login container component", function(){

 afterEach(() => {
   nock.cleanAll();
 });

test("loginFailure action is called when login failed due to no crendetials", () =>{
  nock('http://192.168.0.2:3000')
  .get('/graphql?prettify=true')
  .replyWithError('login failed');

    // Error message: Incorrect username and password please try again
    const mockStore = configureMockStore([thunk]);
    const store = mockStore();
    const output = mount(<Provider store={store}><loginDefault></loginDefault></Provider>)
    let loginButton = output.ref('loginButton');
    expect(store.getActions().length).toBe(0);
    loginButton.simulate('click');
    expect(store.getActions().length).toBe(1);
});

在我运行此测试的那一刻,当尝试模拟无法找到按钮元素的点击时,它失败了。但是这个参考文献存在,当我尝试像按钮这样的简单搜索时,它仍然找不到任何按钮。所以我假设mount正在返回一些无声错误或其他东西。

我只想检查登录失败时是否调用了正确的操作。

我如何让这个测试通过?

答案

你快到了,这适合我。 例如

test("loginFailure action is called when login failed due to no crendetials", () =>{
    nock('http://192.168.0.2:3000')
  	.get('/graphql?prettify=true')
	.replyWithError('login failed');

    // Error message: Incorrect username and password please try again
    const mockStore = configureMockStore([thunk]);
    const store = mockStore();

    const withProvider = (
            <Provider store={store}>
                <loginDefault />
            </Provider>
        );

    const wrapper = mount(withProvider);
    let loginButton = wrapper.find('button'); //here you can use other selector like #myButton or .btn, but be sure it can find it.
    loginButton.simulate('click');
    
    const unsubscribe = store.subscribe(() => {	    
                    const actions = store.getActions();
		    //here your expectation after the action is raised
                    expect(actions.length).to.have.length.above(0);
                });

    expect(store.getActions().length).toBe(0);    

});

以上是关于React-Redux Connected Component测试正确的操作已在click事件上发送的主要内容,如果未能解决你的问题,请参考以下文章

XMPPError connected to chat.facebook.com (Permission denied) login to facebook chat with asmack

React-Redux

React之react-router(connected-react-routerreact-router-dom)

React-Native 之 redux 与 react-redux

React-Native 之 redux 与 react-redux

react-redux学习初步总结