Jest - Testing Asynchronous
阅读原文时间:2023年07月08日阅读:2

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:

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章