我尝试测试axios的请求和响应并得到一个错误。这是我第一次检查我的代码。 error caought
这是我的测试代码(search.test.js)
import React from 'react';
import { shallow } from 'enzyme';
import Search from './search';
import SearchService from '../service/axios.service';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
let element;
describe('Search Component is working normally', () => {
beforeEach(() => {
// mock return promise
const searchResult = Promise.resolve('This is mock search');
SearchService.getInfo = jest.fn();
SearchService.getInfo.mockReturnValue(searchResult);
});
it('renders without crashing', async () => {
element = shallow(<Search />);
expect(element.text()).toContain('');
});
it('implement service', async () => {
element = shallow(<Search />);
await flushAllPromises();
expect(element.text()).toContain('help');
});
// Resolving all
const flushAllPromises = () => new Promise((resolve) => setImmediate(resolve()));
});
这是我的组件代码(search.jsx)
import React, { Component } from "react";
import Suggestions from "../components/suggestions";
import axiosMethods from "../service/axios.service";
class Search extends Component {
state = {
query: "",
results: []
};
redirectPage = query => {
window.open(`https://www.bing.com/search?q=${query}`);
};
getInfo = query => {
axiosMethods.getInfo(query).then(({ data }) => {
this.setState({
results: data
});
});
};
handleInputChange = () => {
this.setState(
{
query: this.search.value
},
() => {
if (this.state.query && this.state.query.length > 1) {
if (this.state.query.length % 2 === 0) {
this.getInfo(this.state.query);
}
} else {
this.setState({
results: []
});
}
}
);
};
render() {
return (
<form>
<input
placeholder="Search for..."
ref={input => (this.search = input)}
onChange={this.handleInputChange}
/>
<Suggestions
results={this.state.results}
redirectPage={this.redirectPage}
/>
</form>
);
}
}
export default Search;
这是我使用axios(axios.service.js)的搜索组件服务
import axios from "axios";
// let API="http://localhost:5000"
let API = "https://search-extenstion.herokuapp.com";
function getInfo(query) {
return axios.post(API, { query: query })
}
let axiosMethods = {
getInfo: getInfo
};
export default axiosMethods;
第一个测试通过了,但是第二个检查我的axios请求的测试失败了,并且输出错误!为什么?