我正在尝试学习 Ext JS 和 Jasmine 框架的单元测试。我编写了这个方法,我想测试是否使用特定值调用 decode
方法,但我不断收到标题中提到的错误。我在这里做错了什么?
方法:
onSuccess: function (response) {
var text = Ext.decode(response.responseText);
this.someGrid.store.loadRawData(text);
}
Jasmine 规范:
it('Function will call decode method', function () {
var response = {};
spyOn(Ext, 'decode').and.returnValue([]);
me.testObj.onSuccess(response);
expect(Ext.decode).toHaveBeenCalledWith([]);
})
最佳答案
您正在向函数 Ext.decode() 传递一个空对象,因此当该函数尝试访问 responseText 属性时,它会收到未定义的信息。
// var response = {}; - empty object created in your test
Ext.decode(response.responseText);
在您的 onSuccess 函数中,对 returnValue() 的调用将返回空数组 - 正如您在 spy 中设置的那样。这个空数组将存储在文本变量中。然后它将被传递到 loadRawData() 函数,而不是像您的 spy 当前所期望的那样 decode()。
var text = Ext.decode(response.responseText);
this.someGrid.store.loadRawData(text);
为了正确测试该函数,您可以在测试中模拟响应对象以包含 responseText 属性。您还可以为 loadRawData() 函数添加 spy 和期望语句,如下所示:
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([]);
})
关于javascript - Jasmine 错误: Expected spy decode to have been called with [ [ ] ] but actual calls were [ undefined ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33229925/