在 Jasmine 中测试空对象失败

tes*_*ing 2 javascript jasmine angularjs karma-jasmine

如果我有{}以下匹配错误的变量设置

// 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({});
});
Run Code Online (Sandbox Code Playgroud)

这是什么原因,您将如何绕过这种行为?根据茉莉花文档

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

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

小智 8

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


小智 0

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