在Jasmine中测试空对象失败

Testing empty object in Jasmine fails

本文关键字:对象 失败 测试 Jasmine      更新时间:2023-09-26

如果变量设置为{},则以下匹配错误

// Somewhere in my angular controller
self = this;
self.myVar = {};

// In my test file
// This errors out. I console.log myVar to make sure that it is indeed {}
expect(myVar).toEqual({});
// Note if I define myVar = {} in the same test spec it works
it('test', function(){
   var myVar = {};
   expect(myCtrl.myVar).toEqual({});
   expect({}).toEqual({});
});

造成这种情况的原因是什么?你会如何忽略这种行为?根据Jasmine doc

it("should work for objects", function() {
  var foo = {
    a: 12,
    b: 34
  };
  var bar = {
    a: 12,
    b: 34
  };
  expect(foo).toEqual(bar);

似乎toEqual应该测试对象内容?

尝试:expect(result).toMatchObject({})

您可以尝试使用与要评估的对象中存在的对象键关联的长度属性:

expect(Object.keys(res).length).toBe(0); // or not.toBeGreaterThan(0)

如果您正在评估一个非空对象,您可以使用:

expect((Object.keys(res)).length).toBeGreaterThan(0) // or not.toBe(0)

我认为您的变量超出了应用程序的范围,在测试用例中,它被执行为未定义的var

var empty = jasmine.empty();
expect(empty.asymmetricMatch(myvar));

=>代码/文档

有两种解决方案:

使用toMatchObject({})

或者尝试使用来自jot-extended的toBeEmpty()。

-首先,安装扩展的jest:

npm install --save-dev jest-extended 

然后在你的测试中使用它,就像其他来自笑话:的匹配者一样

expect(result).toBeEmpty()