使用异步工作验证 React 本机组件



我有一个基本组件,它在componentDidMount阶段调用Web服务并覆盖我所在状态中的contents值:

import React, {Component} from 'react';
import {Text} from "react-native";
class Widget extends Component {
    constructor() {
        super();
        this.state = {
            contents: 'Loading...'
        }
    }
    async componentDidMount() {
        this.setState(...this.state, {
            contents: await this.getSomeContent()
        });
    }
    render() {
        return (
            <Text>{this.state.contents}</Text>
        )
    }
    async getSomeContent() {
        try {
            return await (await fetch("http://someurl.com")).text()
        } catch (error) {
            return "There was an error";
        }
    }
}
export default Widget;

我想使用 Jest 快照在以下每种情况下捕获组件的状态:

  • 装载
  • 成功
  • 错误

问题是我必须引入片状暂停来验证组件的状态。

例如,若要查看成功状态,必须在呈现组件后稍作停顿,以使 setState 方法有机会赶上进度:

test('loading state', async () => {
    fetchMock.get('*', 'Some Content');
    let widget = renderer.create(<Widget />);
    // --- Pause Here ---
    await new Promise(resolve => setTimeout(resolve, 100));
    expect(widget.toJSON()).toMatchSnapshot();
});

我正在寻找克服测试用例中异步性的最佳方法,以便我可以正确验证每个状态的快照。

如果将异步调用移出setState,则可以延迟setState,直到网络调用解析。 然后setState's可以使用可选的回调(在状态更改后触发(来捕获状态。

所以,像这样:

async componentDidMount() {
 var result = await this.getSomeContent()
 this.setState(...this.state, {
     contents: result
 },
 // setState callback- fires when state changes are complete.
 ()=>expect(this.toJSON()).toMatchSnapshot()
 );
}

更新:

如果你想在组件之外指定验证,你可以创建一个 prop,比如说,stateValidation传入验证函数:

jest('loading state', async () => {
    fetchMock.get('*', 'Some Content');
    jestValidation = () => expect(widget.toJSON()).toMatchSnapshot();
    let widget = renderer.create(<Widget stateValidaton={jestValidation}/>); 
});

然后在组件中使用道具:

async componentDidMount() {
 var result = await this.getSomeContent()
 this.setState(...this.state, {
     contents: result
 },
 // setState callback- fires when state changes are complete.
 this.props.stateValidaton
 );
}

相关内容

最新更新