我使用爱可信模拟适配器来模拟HTTP请求来测试我的功能。之后,我定义的函数的行为,然后我创建的类的实例调用的函数,其结果是
**Promise { <pending> }**,
问题是什么?我怎么能回到我所定义的值?
这里是我的代码:
UserService.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);
});
});
您可以检查this link在开玩笑文档的更多例子。
也有是在你的getUserInfo()
方法错误,params中要传递的userId
的对象,但你需要传递字符串或INT。你应该做的是:
return axios.get('https://www.usefortesting.com', {
params: { userId: params.userId },
})...
return axios.get('https://www.usefortesting.com', {
params,
})...