2017-08-27 74 views
1

Enzyme newbie here。我试图在调用该组件上的方法之后测试React组件的状态是否正在更新。如何在调用更新状态的组件方法后测试React状态 - 使用Enzyme

这是组件的一个片段,我测试:

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    state = { 
    recipes: {}, 
    user: null 
    }; 

    handleUnauth =() => { 
    this.setState({ 
     user: null 
    }); 
    }; 

    render() { 
    //render children, pass down methods as props etc... 
    } 

} 

下面是测试:

import createRouterContext from 'react-router-test-context'; 
import { shallow, mount } from 'enzyme'; 
import expect from 'expect'; 
import React from 'react'; 

import App from 'App'; //import with webpack alias 

describe('App',() => { 

    let wrapper, context; 

    beforeEach(() => { 
    context = createRouterContext(); 
    wrapper = mount(<App/>, { context }); 
    }); 

    it('should remove logged in user details on logout',() => { 
    const user = { 
     uid: 'abc123', 
     name: 'John Doe' 
    }; 

    wrapper.setState({ user },() => { 
     wrapper.instance().handleUnauth(); 
     const userState = wrapper.state('user'); 
     expect(userState).toEqual(null); 
    }); 

    }); 

}); 

我的测试失败,出现以下错误:

enter image description here

我知道更新状态不是同步但我不确定这是否与此有关,或者如果有更好的方法来使用酶测试。如果有人能够请正确指导我的话,我会非常感激。噢,我在测试中调用wrapper.instance().handleUnauth()之后立即致电wrapper.update()来尝试此操作,但这也不起作用。

+1

回调参数是否正常工作,如果你调用'wrapper.update()状态( '用户' )'? –

+0

@OrB只是用'wrapper.update()。state('user')'试过了 - 它不起作用。该应用程序工作正常 - 我可以看到,在使用React DevTools进行检查时,用户值在注销时设置为null,但在测试中不起作用。 – Larrydx

+0

@Larrydx请检查答案。 –

回答

1

React#setState

的setState(更新器,[回调])

setState() enqueues changes to the component state. The setState doesn't immediately update the state. setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.Instead, use componentDidUpdate or a setState callback (setState(updater, callback))

解决方案1:从setState

删除回调;

 wrapper.setState({ user }); 
     wrapper.instance().handleUnauth(); 
     const userState = wrapper.state('user'); 
     expect(userState).toEqual(null); 

解决方案2:

读取更新状态的setState callback

wrapper.setState({ user }, (userState) => { 

     wrapper.instance().handleUnauth(); 
     //const userState = wrapper.state('user'); // comment it. 
     expect(userState).toEqual(null); 
}); 
+0

解决方案2没有任何效果,但解决方案1对我来说非常合适。我认为回调并不需要,因为调用handleUnauth(组件方法)会导致状态更新。然后可以在断言中比较更新的状态。感谢Riyaj! – Larrydx

+0

谢谢@Larrydx。如果它的工作正常,请加快速度。请让我知道解决方案2的错误 –

+0

对于解决方案2,我得到了上面在问题中显示的相同错误 - 不知道为什么。决定做一些酵素教程来解决这个问题,一旦我了解了如何/为什么会更新。 – Larrydx

相关问题