gpt4 book ai didi

reactjs - 如何在调用更新状态的组件方法后测试 React 状态 - 使用 Enzyme

转载 作者:行者123 更新时间:2023-12-03 13:30:05 24 4
gpt4 key购买 nike

这里是 enzyme 新手。我正在尝试测试 React 组件的状态在调用该组件上的方法后是否正在更新。

这是我正在测试的组件的片段:

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

我知道状态更新不是同步的,但我不确定这是否与此有关,或者是否有更好的方法使用 enzyme 来测试它。如果有人能指出我正确的方向,我将非常感激。哦,我在测试中调用 wrapper.instance().handleUnauth() 后立即调用 wrapper.update() 进行了尝试,但这也不起作用。

最佳答案

来自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回调的回调参数中读取更新后的状态

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

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

关于reactjs - 如何在调用更新状态的组件方法后测试 React 状态 - 使用 Enzyme,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com