Mocha - 如何在 ajax 调用后检查元素是否存在

Mocha - how to check if element exist after ajax call

如何检查 select 在被 ajax 函数更新后是否有一些选项。我的 select 组件如下所示

class Select extends React.component(){
    constructor(){
        super()
        this.state.item=[]
    }
    componentWillMount(){
        axios.get(list)
        .then(function (response) {
            this.setState({item:response.data})
            // reponse data ['america','singapore','vietnam']
        })
    }   
    render(){
        return(
            <select>
                this.state.item.map((i) => {
                    <option value="i">i</option>
                })
            </select>
        )
    }
}

这是我的尝试:

import {expect} from 'chai'
import {shallow} from 'enzyme'
import sinon from 'sinon'
import Select from 'Select'
describe('select list', () => {
    it('should have options', () => {
        const wrapper = shallow(<Select />)
        wrapper.update()
        const actual = wrapper.find('option').length
        expect(actual).to.not.equal(0)
    })
})

这有什么问题,我得到了 var actual = 0。它应该是 3。所以我想我错过了 axios 的东西。我应该在规格中添加什么?

您的 GET 请求可能仍在等待响应,但 mocha 已经完成测试执行。

您可以添加超时并在一段时间后断言,然后在完成测试后调用 done() 回调。请查看 mocha's asynchronous code 部分。

describe('select list', () => {
    it('should have options', (done) => {
        const wrapper = shallow(<Select />)
        wrapper.update()
        setTimeout(() => {      
            const actual = wrapper.find('option').length
            expect(actual).to.not.equal(0)
            done();
        }, 2000)
    })
})

我建议您查看 axios-mock-adapter,它允许您模拟请求而不是向服务器发送实际请求。