2016-02-02 98 views
0

我将karma和jasmine用作我的测试框架。这是我的代码:如何检查对象是否包含使用Jasmine的项目

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

+0

试'(ctrl.reply.x).toBe(null)'因为它是一个对象 – maioman

+0

@maioman返回一个错误,说undefined不为null。当我做'(ctrl.reply.x).toBe(undefined)'时,那么它不会返回错误,但是如果我做'(ctrl.reply.y).toBe(undefined)'它也不会返回错误'因为我希望能够检查'ctrl.reply.x'确实存在。 – user2719875

回答

1

您在创建的东西和预期的东西中存在缺陷。注意这一行:

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

该公司预计ctrl有一个属性“上岗”,也就是其具有有一个名为id性的指标0的数组。 这些条件每一个失败

你,而不是下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'); 
}); 
+1

谢谢!顺便说一句,'expect(ctrl.reply).toContain('x');'仍然失败,但我只是把它改成'expect(ctrl.reply.x).toBe('test post');' 。 – user2719875

+0

@ user2719875赶上!很高兴它的工作。 –

相关问题