React-Redux Connected Component测试正确的操作已在点击事件

时间:2017-02-03 11:35:52

标签: reactjs redux react-redux jestjs enzyme

我是一个用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正在返回一些无声错误或其他什么。

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

如何让这个测试通过?

1 个答案:

答案 0 :(得分:0)

你快到了,这对我有用 例如

&#13;
&#13;
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);    

});
&#13;
&#13;
&#13;

希望得到这个帮助。