gpt4 book ai didi

reactjs - 如何测试其中包含 api 请求的 React 函数?

转载 作者:行者123 更新时间:2023-11-28 20:52:00 25 4
gpt4 key购买 nike

我在 React 组件中有一个类似的功能。如何测试成功的请求和不成功的请求?

deleteQuestion(id) {
axios.delete('/api/questions/' + id)
.then(response => {
this.setState({message: "Deletion Successful!"});
}).catch(error => {
var errorMessage = 'Question not deleted: ' + error.response.data.message;
this.setState({error: errorMessage});
});
}

我正在考虑为测试做这样的事情,但这显然行不通。基本上final函数里面的console.log和assertion是跑不起来的。

import React from 'react';
import { mount, shallow } from 'enzyme';
import axios from 'axios';
import axios from 'axios';
import QuestionList from './QuestionList';
import sinon from 'sinon';


beforeEach(function () {
// import and pass your custom axios instance to this method
moxios.install()
})

afterEach(function () {
// import and pass your custom axios instance to this method
moxios.uninstall()
})

it('should modals and <table>', () => {
const wrapper = shallow(<QuestionList/>);
wrapper.instance().deleteQuestion()
moxios.wait(function () {
let request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: [
{ id: 1, question: 'Fred', answer: 'Flintstone' },
{ id: 2, question: 'Wilma', answer: 'Flintstone' }
]
}).then(function () {
console.log('hello')
expect(wrapper.state().message).to.equal('Deletion Successful');
done()
})
})
});

最佳答案

您可以使用一些模拟 http 服务器库。例如https://www.npmjs.com/package/mock-http-server

关于reactjs - 如何测试其中包含 api 请求的 React 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42809422/

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