问题描述
我已经为调用jQuery getJSON
方法的函数编写了单元测试.我正在测试的唯一一件事是使用预期的URL进行调用.我的单元测试使用Jasmine Spy来模拟API调用.但是,当我运行单元测试时,出现此错误:
I've written a unit test for a function that calls the jQuery getJSON
method. The only thing that I'm testing is that it is called with the expected URL. My unit test uses a Jasmine Spy to mock the API call. However, when I run my unit tests I get this error:
1) should make a request to the expected URL when running on localhost
test module getDataFromApi function
TypeError: Cannot read property 'fail' of undefined
在单元测试中,我创建了一个Jasmine Spy,它返回了done
和fail
方法.我在这里做什么错了?
In my unit test I've created a Jasmine Spy, which returns the done
and fail
methods. What am I doing wrong here?
这是我的单元测试:
describe('getFundDataFromApi function', function () {
beforeEach(function () {
spyOn($, "getJSON").and.callFake(function () {
return {
done: function () {},
fail: function () {}
};
});
});
it('should make a request to the expected URL when running on localhost', function () {
var expectedUrl = '/assets/mock-data/mock-data.json';
module.getDataFromApi();
expect($.getJSON).toHaveBeenCalled();
expect($.getJSON).toHaveBeenCalledWith({url:expectedUrl});
});
});
我要测试的功能:getDataFromApi
getDataFromApi: function () {
var mod = this;
var url = this.settings.apiUrl;
$.getJSON({
url: url
})
.done(function (data) {
mod.processApiData(data);
})
.fail(function () {
mod.displayErrorMessage();
});
},
推荐答案
在函数getDataFromApi
中,您将fail
的调用链接在done
之后,但是在 mocked 版本中done
,它不返回任何内容(undefined
),因此,您得到 TypeError:无法读取未定义的属性'fail'.
In your function getDataFromApi
you are chaining the call of fail
after done
but, in the mocked version of done
, it returns nothing(undefined
), so, you get TypeError: Cannot read property 'fail' of undefined.
您可以使done
函数返回具有fail
属性即函数的对象.
You can make the done
function to return an object with a fail
property that is a function.
beforeEach(function() {
spyOn($, "getJSON").and.callFake(function() {
return {
done: function() {
return { fail: function() {} };
}
};
});
});
或者,一行ES6版本spyOn($, "getJSON").and.callFake(() => ({ done: () => ({fail: () => {}}) }));
Or, one line ES6 versionspyOn($, "getJSON").and.callFake(() => ({ done: () => ({fail: () => {}}) }));
或者,如果您打算在测试中做更多的事情,例如测试成功或失败的响应,则可能返回 jQuery Deferred 可以帮助您
Or, if you are planning to do more in your tests, like testing success or failed responses, probably returning a jQuery Deferred can help you
beforeEach(function() {
spyOn($, "getJSON").and.callFake(function() {
const deferred = $.Deferred();
deferred.resolve({'success': true});
return deferred;
});
});
致电deferred.reject({'success': false});
将使您有机会测试错误.
Calling deferred.reject({'success': false});
will give you the chance to test for errors.
希望有帮助
这篇关于使用Jasmine和Karma使用fail方法对jQuery getJSON函数错误进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!