如何使用茉莉花检查对象是否包含项目

How to check if object contains an item using Jasmine

本文关键字:是否 包含 项目 对象 检查 何使用 茉莉花      更新时间:2023-09-26

我正在使用业力和茉莉花作为我的测试框架。这是我的代码:

it('add() should add x to the reply object', function() {
    spyOn(ctrl, 'addxReply');
    ctrl.reply = {};
    ctrl.reply.post = 'test post';
    ctrl.add();
    expect(ctrl.addxReply).toHaveBeenCalled();
    console.log(ctrl.reply);
    expect(ctrl.reply).toContain('x');
});

这是我的ctrl.add():

self.add = function() {
    self.reply['x'] = self.posts[0].id;
    self.addxReply();
};

问题是,当我运行代码时,它返回的内容如下:

LOG: Object{post: 'test post', x: undefined}
Chromium 48.0.2564 (Ubuntu 0.0.0) Controller: MainCtrl add() should add x to the reply object FAILED
    Expected Object({ post: 'test post', x: undefined }) to contain 'x'.

如您所见,我的回复对象确实包含x但行expect(ctrl.reply).toContain('x');仍然失败。知道如何正确验证我的对象是否包含x吗?

您在创建的内容与预期内容方面存在错误。请注意此行:

self.reply['x'] = self.posts[0].id;

它期望ctrl有一个属性"posts",该数组是一个具有索引的数组,0该数组具有一个名为 id 的属性。这些条件中的每一个都失败了

相反,您在ctrl的属性reply下定义了一个单一属性(而不是数组):

ctrl.reply.post

您需要更改测试代码:

it('add() should add x to the reply object', function() {
    spyOn(ctrl, 'addxReply');
    ctrl.reply = {};
    //ctrl needs an array named "posts" with one index
    //containing an object with an "id" property
    ctrl.posts = [ { "id": 'test post' } ];
    ctrl.add();
    expect(ctrl.addxReply).toHaveBeenCalled();
    console.log(ctrl.reply);
    expect(ctrl.reply).toContain('x');
});