【问题标题】:How to assert state in unit test (React JS) while state is updating in axios call?如何在 axios 调用中更新状态时在单元测试(React JS)中断言状态?
【发布时间】:2021-02-04 00:18:12
【问题描述】:

嗨,我在单元测试用例中断言状态时遇到问题,而它在 axios 调用中更新。 这是我的 axios 调用

import axios from 'axios'
getData = () => {
    axios.get('/events/sept/week2/1097338')
        .then(res =>{
            if(res.status == 200){
                let resposne = res.data.resposne
                this.setState({weekData:response})
            }
        })
        .catch(error => {console.log(error)})
}

这是我的测试用例

test("test axios for week data",() => {
    const mock = new MockAdapter (axios)
    mock.onGet('/events/sept/week2/1097338').reply(200,{response:['raspberry']})
    const wrapper = shallow(<Component/>)
    wrapper.instance().getData()
    expect(wrapper.state('weekData')).toBe(['raspberry'])
})

当我调用时,组件中的状态 weekData 正在更新 wrapper.instance().getData(),我已经检查过了。它没有在包装器中更新,我的断言失败,如:预期:['raspberry'],收到:[]。如何更新包装器中的状态我尝试过 setTimeout 但没有用

【问题讨论】:

标签: reactjs unit-testing axios jestjs enzyme


【解决方案1】:

当调用 Axios 的函数无法访问时,应将其返回的 Promise 链接起来以避免竞争条件。由于MockAdapter 没有专门提供,所以应该另外做:

const wrapper = shallow(<Component/>)
jest.spyOn(axios, 'get');
wrapper.instance().getData()
expect(axios.get).toBeCalledTimes(1);
await axios.get.mock.results[0].value;
expect(wrapper.state('weekData')).toBe(['raspberry'])

对于可直接访问的函数,它返回的 Promise 可以被链接。 getData 是一种反模式,因为它包含无法链接的松散承诺。应该是:

getData = () => {
    return axios.get('/events/sept/week2/1097338')
    ...

那么它可以被测试为:

const wrapper = shallow(<Component/>)
await wrapper.instance().getData()
expect(wrapper.state('weekData')).toBe(['raspberry'])

【讨论】:

  • 谢谢 Estus spyOn 为我工作,第一个期望工作但在等待时仍然面临问题,因为我没有使用异步
  • 然后考虑使用它,因为 await 应该在 async 函数中。这是合理的,因为测试是异步的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 2020-09-28
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
相关资源
最近更新 更多