使用Jest返回异步回调测试Angular 1.6未被调用

问题描述 投票:0回答:1

我正试图用Jest测试一个Angular 1.6服务,但是我每次都遇到错误,有人遇到这个问题? (我在我的服务中没有使用setTimeout,如下所示)

错误

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

测试规格

describe('Fail Cases', () => {
  beforeEach(angular.mock.module('marvel'))
  let _marvelservice
  beforeEach(inject((MarvelService) => {
    _marvelservice = MarvelService
  }))

  test('should return false when user do not put the id for details correctly', (done) => {
    _marvelservice.getDetail()
      .catch((err) => {
        expect(err.xhrStatus).toBe('error')
        done()
      })
  })
})

奇迹服务

(() => {
  angular.module('marvel')
    .factory('MarvelService', ($http, $q, Config) => {
      /**
       * Get details from a characters by consulting the Marvel API.
       * @return {Object} Doc with detail character recovered.
       */
      function getDetail (id) {
        const urlAddress = `/${id}`
        return request(urlAddress, 'GET', { ts: 1, apikey: `${Config.MARVEL.PUBLIC_KEY}`, hash: `${Config.MARVEL.MD5}` })
      }

      /**
       * Responsible for request.
       * @return {Object} Doc with the returned promise.
       */
      function request (path, method, querystring) {
        const options = {
          method,
          url: `${Config.MARVEL.URL}${path}`,
          params: querystring
        }

        return $http(options)
          .then(success => { return success.data }, (err) => {
            return err
          })
      }

      return {
        getDetail
      }
    })
})()
angularjs jest
1个回答
1
投票

它告诉你,在你的test块中,done()永远不会被运行,很可能是因为.catch()回调中的代码永远不会被运行。这可能是因为您的API请求成功而不是失败。您应该使请求无法到达.catch()块:通过执行请求API将引发错误,或者通过监视请求并强制它失败,如下所示:

test('should return false when user do not put the id for details correctly', (done) => {
    // You must inject $q somewhere
    spyOn(_marvelservice, 'getDetail').and.returnValue($q.reject());

    _marvelservice.getDetail()
      .catch((err) => {
        expect(err.xhrStatus).toBe('error');
        done();
      });
  });
© www.soinside.com 2019 - 2024. All rights reserved.