【发布时间】: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 对不起我的错误,但错误仍然存在。