我正在使用axios mock适配器来模拟HTTP请求来测试我的函数。在我定义了函数的行为之后,然后我创建了一个类的实例来调用该函数,结果是
**Promise { <pending> }**,
问题出在哪里?如何返回我定义的值?
这是我的代码:
用户服务.js
export default class UserService {
getUserInfo = userId => {
const params = {
userId,
};
return axios
.get('https://www.usefortesting.com', {
params: { userId: params },
})
.then(response => response.data.userInfo)
.catch(error => error);
};
}
UserService.test.js
import React from 'react';
import axios from 'axios';
import UserService from './UserService';
import MockAdapter from 'axios-mock-adapter';
describe('testing', () => {
let axiosMock;
const Info = {
userInfo: {
id: '123',
name: 'omg',
},
};
beforeEach(function() {
axiosMock = new MockAdapter(axios);
});
afterEach(() => {
axiosMock.reset();
axiosMock.restore();
});
it('testing', () => {
axiosMock
.onGet('https://www.usefortesting.com', {
params: { userId: 'user_1' },
})
.reply(200, Info);
let userService = new UserService();
let response = userService.getUserInfo('user_1');
console.log(response);
});
});
您需要等待测试中的响应。使用回调或异步/等待,如下所示。
您的测试应该是这样的:
it('testing', async () => { // notice async here
axiosMock
.onGet('https://www.usefortesting.com', {
params: { userId: 'user_1' },
})
.reply(200, Info);
let userService = new UserService();
let response = await userService.getUserInfo('user_1'); // notice await here
console.log(response);
});
或
it('testing', () => {
...
userService.getUserInfo('user_1').then(response => {
console.log(response);
});
});
您可以在 jest 文档中查看此链接以获取更多示例。
您的getUserInfo()
方法也存在错误,在参数中,您正在传递一个对象userId
但您需要传递字符串或 int。你应该做的是:
return axios.get('https://www.usefortesting.com', {
params: { userId: params.userId },
})...
或
return axios.get('https://www.usefortesting.com', {
params,
})...