当我使用自定义axios实例时,与moxios的开玩笑会保持超时

时间:2019-02-21 02:54:14

标签: unit-testing jestjs 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实例,但是我找不到任何原因不会这样做。

感谢您的帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试过通过将其添加到测试文件中来更改Jest环境设置?

/**
 * @jest-environment node
 */
import moxios from 'moxios';
...

除非添加,否则玩笑会阻止请求发出。无论哪种方式,我都使用nock而不是moxios,我推荐它。