我正在使用axios模拟适配器模拟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);
});
});
答案 0 :(得分:1)
您需要等待测试中的回复。如下所示使用回调或异步/等待。
您的测试应如下所示:
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(User... user);
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);
});
您可以查看Jest文档上的this link以获得更多示例。
您的it('testing', () => {
...
userService.getUserInfo('user_1').then(response => {
console.log(response);
});
});
方法中也有错误,在参数中,您正在传递getUserInfo()
的对象,但您需要传递字符串或整数。您应该做的是:
userId
return axios.get('https://www.usefortesting.com', {
params: { userId: params.userId },
})...