1、示例一(返回值和返回promise的处理)
import axios from 'axios'
export const fetchData = (fn) => {
axios.get("http://www.dell-lee.com/react/api/demo.json").then(response => {
fn(response.data)
})
}
import { fetchData } from './fetchData'
test('fetchData 返回结果为 {success: true}', (done) => {
fetchData((data) => {
expect(data).toEqual({
success: true
})
done();
})
})
2、示例二(正常处理和异常处理)
import axios from 'axios'
export const fetchData = () => {
return axios.get("http://www.dell-lee.com/react/api/demo.json");
}
import { fetchData } from './fetchData'
test('fetchData 返回结果为 {success: true }', () => {
return fetchData().then((response) => {
expect(response.data).toEqual({
success: true
})
})
})
test('fetchData 返回结果为 {success: true}', () => {
expect.assertions(1)
return fetchData().catch(e => {
expect(e.toString().indexOf('404') > -1).toBe(true)
})
})
3、示例三(resolves/rejects)
import axios from 'axios'
export const fetchData = () => {
return axios.get("http://www.dell-lee.com/react/api/demo.json")
}
import { fetchData } from './fetchData'
test('fetchData 返回结果为 {success: true}', () => {
return expect(fetchData()).resolves.toMatchObject({
data: {
success: true
}
})
})
import { fetchData } from './fetchData'
test('fetchData 返回结果为 404', () => {
return expect(fetchData()).rejects.toThrow();
})
4、示例四(async/await)
import axios from 'axios'
export const fetchData = () => {
return axios.get("http://www.dell-lee.com/react/api/demo.json")
}
import { fetchData } from './fetchData'
test('fetchData 返回结果为 {success: true}', async () => {
await expect(fetchData()).resolves.toMatchObject({
data:{
success: true
}
})
})
test('fetchData 返回的结果 404', async () => {
await expect(fetchData()).rejects.toThrow()
})
5、示例五(async/await 异步求值)
import axios from 'axios'
export const fetchData = () => {
return axios.get("http://www.dell-lee.com/react/api/demo.json")
}
import { fetchData } from './fetchData'
test('fetchData 返回结果为{ success: true}', async () => {
const response = await fetchData();
expect(response.data).toEqual({
success: true
})
})
test('fetchData 返回结果为 404', async () => {
expect.assertions(1);
try {
await fetchData()
} catch (e) {
expect(e.toString().indexOf('404') > -1).toBe(true)
}
})
网友评论