【问题标题】:Testing Angular 1.6 with Jest return async callback was not invoked未调用使用 Jest 返回异步回调测试 Angular 1.6
【发布时间】:2018-03-01 10:48:33
【问题描述】:

我正在尝试使用 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
      }
    })
})()

【问题讨论】:

  • 也许超时是你可以覆盖的默认值
  • 这被讨论了很多次,并不是专门针对 Jest。 $q Promise 是同步的,不需要done,但是没有 $rootScope.$digest() 就不会执行 Promise 链。我建议使用github.com/bvaughn/jasmine-promise-matchers
  • @JohnKane 我试过jest.setTimeout = 10000,但我在上面遇到了同样的错误
  • 会不会是:jest.setTimeout(10000);
  • @JohnKane 对不起我的错误,但错误仍然存​​在。

标签: angularjs jestjs


【解决方案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();
      });
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多