我如何在我的控制器中模拟axios调用?



所以我的axios调用是一个已经分离的模块,并通过模拟axios本身进行测试。但是,当我将这个函数导入到控制器中时,测试控制器本身的最佳方法是什么?我知道它需要被嘲笑,但我不确定嘲笑它的最有效的方法,所以我可以测试请求和res(也被嘲笑)。

axios调用是getAddressWithPostcode

控制器:

const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
const { params } = req
await getAddressWithPostcode(params)
.then((data) => {
if (!isUndefined(data.status)) {
return res.status(data.status).send(data.data.Message)
}
return res.send(data)
})
.catch(err => {
next(err)
})
}

Axios叫:

const getAddressWithPostcode = async (params: Params) => {
const { postCode, number } = params
const addressUrl = `${process.env.URL}/${postCode}${number
? `/${number}?api-key=${process.env.API_KEY}`
: `?api-key=${process.env.API_KEY}`}`
try {
const { data } = await axios.get(addressUrl)
return data
} catch (e) {
const { response } = e
return response
}
}
// users.test.js
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get.mockResolvedValue(resp);
// or you could use the following depending on your use case:
// axios.get.mockImplementation(() => Promise.resolve(resp))
return Users.all().then(data => expect(data).toEqual(users));
});

这个例子使用jest来测试axios调用,同样可以扩展到任何库。希望它能让你开始

可以在这里找到更多关于jest单元测试的细节

最新更新