最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Testing empty object in Jasmine fails - Stack Overflow

programmeradmin1浏览0评论

If I have a variable setting to {} the following match errors

// 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({});
});

What is the reason for this and how would you by pass this behavior? According to Jasmine doc

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

It seems like toEqual should test for object content?

If I have a variable setting to {} the following match errors

// 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({});
});

What is the reason for this and how would you by pass this behavior? According to Jasmine doc

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

It seems like toEqual should test for object content?

Share Improve this question edited Jan 7, 2016 at 0:17 testing asked Jan 6, 2016 at 23:41 testingtesting 2,3434 gold badges24 silver badges33 bronze badges 1
  • Please post your controller. Unless myVar is a global variable (which is bad) expect(myVar).toEqual({}); won't work – Wayne Ellery Commented Jan 7, 2016 at 0:10
Add a comment  | 

5 Answers 5

Reset to default 16

Try: expect(result).toMatchObject({})

You could try with the length property associated with the Object Keys present in your object to be evaluated:

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

If you are evaluating a non empty object you may use:

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

I think your variable is getting out of scope from app and in the test case it is getting executed as undefined var

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

=> Code / Doc

there are two solutions:

Either use toMatchObject({})

or try using toBeEmpty() from jest-extended.

-first, install jest-extended:

npm install --save-dev jest-extended 

then use it in your test like other matchers from jest:

expect(result).toBeEmpty() 
发布评论

评论列表(0)

  1. 暂无评论