测试通过Jest和酶改变状态的异步componentDidMount

问题描述 投票:1回答:1

[我在代码中所做的只是在运行componentDidMount之后,我正在向GitHub发出axios获取请求,并将一些数据重新设置为状态。但是,当我运行测试时,它仍然说状态是一个空数组。

这是我的下面的内容:

export default class HelloWorld extends Component {
    constructor(props) {
        super(props)
        this.state = {
            goodbye: false,
            data: []
        }

    }

    async componentDidMount() {
        await this.func()
    }

    func = async () => {
        let data = await axios.get('https://api.github.com/gists')
        this.setState({data: data.data})
        console.log(this.state)
    }

    goodbye = () => {
        this.setState((state, currentProps) => ({...state, goodbye: !state.goodbye}))
    }

    render() {
        return (
            <Fragment>
                <h1>
                    Hello World
                </h1>
                <button id="test-button" onClick={this.goodbye}>Say Goodbye</button>
                {
                    !this.state.goodbye ? null :
                    <h1 className="goodbye">GOODBYE WORLD</h1>
                }
            </Fragment>
        )
    }
}

这是我的测试:

it('there is data being returned', async () => { 
    const component =  await mount(<HelloWorld />)       

    component.update()

    expect(component.state('data')).toHaveLength(30)

})

我对使用Jest非常陌生,不确定自己在做什么错。这个程序是专门为用酶测试Jest而构建的。如何正确测试此组件?

javascript reactjs testing jestjs enzyme
1个回答
0
投票

首先,您需要以某种方式模拟等待axios.get('https://api.github.com/gists')。

他们可能需要在component.update()之后执行this之类的操作才能“等待”。

© www.soinside.com 2019 - 2024. All rights reserved.