我正在尝试使用Jasmine框架学习Ext JS和单元测试。我写了这个方法,我想测试是否使用某个值调用decode
方法,但我不断收到标题中提到的错误。我在这里做错了什么?
方法:
onSuccess: function (response) {
var text = Ext.decode(response.responseText);
this.someGrid.store.loadRawData(text);
}
Jasmine spec:
it('Function will call decode method', function () {
var response = {};
spyOn(Ext, 'decode').and.returnValue([]);
me.testObj.onSuccess(response);
expect(Ext.decode).toHaveBeenCalledWith([]);
})
答案 0 :(得分:2)
您正在将空对象传递给函数 Ext.decode(),因此当函数尝试访问 responseText 属性时,它会收到未定义的内容。
// var response = {}; - empty object created in your test
Ext.decode(response.responseText);
在你的onSuccess函数中,对 returnValue()的调用将返回空数组 - 在你的间谍中设置。这个空数组将存储在text变量中。然后它将被传递给 loadRawData()函数,而不是像你的间谍当前所期望的 decode()。
var text = Ext.decode(response.responseText);
this.someGrid.store.loadRawData(text);
为了正确测试该函数,您可以在测试中模拟响应对象以包含 responseText 属性。您还可以为 loadRawData()函数添加spy和expect语句,如下所示:
it('Function will call decode method', function () {
// mock response object has responseText propety
var response = { responseText: 'mockResponseText' };
spyOn(Ext, 'decode').and.returnValue([]);
// spy to LoadRawData added to check return value of decode is passed on correctly
spyOn(me.testObj.someGrid.store, 'loadRawData');
me.testObj.onSuccess(response);
// Ext.decode should be called with the response text
expect(Ext.decode).toHaveBeenCalledWith('mockResponseText');
// loadRawData should be called with return value of decode function
expect(me.testObj.someGrid.store.loadRawData).toHaveBeenCalledWith([]);
})