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);
});
});
});
我的測試失敗,出現以下錯誤:
我知道更新狀態不是同步但我不確定這是否與此有關,或者如果有更好的方法來使用酶測試。如果有人能夠請正確指導我的話,我會非常感激。噢,我在測試中調用wrapper.instance().handleUnauth()
之後立即致電wrapper.update()
來嘗試此操作,但這也不起作用。
回調參數是否正常工作,如果你調用'wrapper.update()狀態( '用戶' )'? –
@OrB只是用'wrapper.update()。state('user')'試過了 - 它不起作用。該應用程序工作正常 - 我可以看到,在使用React DevTools進行檢查時,用戶值在註銷時設置爲null,但在測試中不起作用。 – Larrydx
@Larrydx請檢查答案。 –