Jest - Testing Asynchronous
When we test asynchronous, we use Axios to get the response.
install the Axios
npm i axios
Cause we already config the babel for presets, so we can directly use 'import'
fetchData.js
import axios from "axios";
export const fetchData = (fn) => {
axios.get('https://ning-xin.com/mock/jestTest.json').then((response) => {
fn(response.data)
})
}
export const fetchData2 = ()=>{
return axios.get('https://ning-xin.com/mock/jestTest.json')
}
fetchData.test.js (I named fetchData.test,.js. There is a comma, therefore, there is an error like 'No tests found')
import {fetchData, fetchData2} from "./asyncMethod";
test('fetch data test', (done) => {
fetchData((data) => {
try {
expect(data).toEqual({
"code": "200",
"data": "success"
}
)
done();
} catch (error) {
done(error);
}
})
})
test('fetch data test', (done) => {
fetchData((data) => {
try {
expect(data.code).toEqual("200")
done();
} catch (error) {
done(error);
}
})
})
test('Fetch promise data test', async (done) =>{
const response = await fetchData2();
const data = response.data;
console.log(data, 'response.data')
expect(data).toEqual({
"code": "200",
"data": "success"
}
)
})
Result: