2

我有一个使用自定义 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 实例,但我找不到任何原因。

任何帮助表示赞赏,在此先感谢。

4

1 回答 1

0

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

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

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

于 2019-08-08T14:32:41.527 回答