unit-testing - 当我使用自定义 axios 实例时,与 moxios 的玩笑不断超时
问题描述
我有一个使用自定义 axios 实例的服务,我正在尝试测试该实例,但我不断收到错误消息。
这是错误:
: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
这是测试:
import moxios from 'moxios';
import NotificationService, { instance } from '../NotificationService';
beforeEach(() => {
moxios.install(instance);
});
afterEach(() => {
moxios.uninstall(instance);
});
const fetchNotifData = {
data: {
bell: false,
rollups: []
}
};
describe('NotificationService.js', () => {
it('returns the bell property', async done => {
const isResolved = true;
const data = await NotificationService.fetchNotifications(isResolved);
moxios.wait(() => {
let request = moxios.requests.mostRecent();
console.log(request);
request
.respondWith({
status: 200,
response: fetchNotifData
})
.then(() => {
console.log(data);
expect(data).toHaveProperty('data.bell');
done();
});
});
});
});
这是我要测试的代码:
import axios from 'axios';
// hardcoded user guid
const userId = '8c4';
// axios instance with hardcoded url and auth header
export const instance = axios.create({
baseURL: 'hidden',
headers: {
Authorization:
'JWT ey'
});
/**
* Notification Service
* Call these methods from the Notification Vuex Module
*/
export default class NotificationService {
/**
* @GET Gets a list of Notifications for a User
* @returns {AxiosPromise<any>}
* @param query
*/
static async fetchNotifications(query) {
try {
const res = await instance.get(`/rollups/user/${userId}`, {
query: query
});
console.log('NotificationService.fetchNotifications()', res);
return res;
} catch (error) {
console.error(error);
}
}
}
我试过缩短开玩笑的超时时间,但没有奏效。我认为是 moxios 没有正确安装 axios 实例,但我找不到任何原因。
任何帮助表示赞赏,在此先感谢。
解决方案
您是否尝试通过将其添加到测试文件来更改 Jest 环境设置?
/**
* @jest-environment node
*/
import moxios from 'moxios';
...
除非您添加它,否则 Jest 往往会阻止请求发出。无论哪种方式,我都使用nock
而不是,moxios
我推荐它。
推荐阅读
- php - 如何从 8 位玩家中创建 7 轮的独特玩家组合
- jquery - 我可以对多个 Ajax 调用使用相同的类名吗
- pandas - 如何在pyspark中使用udf比较一对列?
- python - 我无法制作键内有 # 符号的字典
- python - 将两个日期之间的差转换为整数
- python - 在给定距离内获取邻居 BFS 算法
- python - Client = discord.client() TypeError: 'module' object is not callable
- stata - 在 coefplot 中分配不同的标签
- php - 使用 OOP PHP 的 Ajax 请求
- java - 如何撤消任何功能