javascript - Jasmine 错误: Expected spy decode to have been called with [ [ ] ] but actual calls were [ undefined ]

标签 javascript extjs jasmine

我正在尝试学习 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/

相关文章:

javascript - Jasmine - 使用构造函数正确模拟对象

javascript - 如何正确使用*ngIf?

java - 我可以使用 extjs 将字段值作为数组提交吗?

javascript - 回调未被调用

javascript - 删除 Accordion 元素之间的填充

javascript - 如何在 Extjs checkcolumn 中获取 id?

node.js - 使用 Protractor 给出错误的端到端测试

angularjs - 为什么我的 HTML 测试报告总是落后一个 XML 文件?

javascript - 内容对齐的非 45º 三 Angular 形

javascript - 使用 Promise 创建用户和登录流程