Ramon Balthazar
Ramon Balthazar

Reputation: 4260

Jest - How to test if a function made changes to an argument

Suppose I have this function

function changeFooBarToOne(foo) {
  foo.bar = 1;
}

How do I test if it changed the value to 1?

describe('changeFooBarToOne', () => {
  it('modifies the bar property value to 1', () => {
    const foo = { bar: 0 };
    // call the expect and evaluate foo to equal { bar: 1 }
  })
})

Upvotes: 0

Views: 50

Answers (1)

Ritwick Dey
Ritwick Dey

Reputation: 19012

Don't forget, JavaScript Objects are reference type.

function changeFooBarToOne(foo) {
   foo.bar = 1;
}

describe('changeFooBarToOne', () => {
  it('modifies the bar property value to 1', () => {
    const foo = { bar: 0 };
    changeFooBarToOne(foo);
    expect(foo.bar).toBe(1);
  })
})

//another way
describe('changeFooBarToOne_1', () => {
  it('modifies the bar property value to 1', () => {
    const foo = { bar: 0 };
    changeFooBarToOne(foo);
    expect(foo).toEqual({bar : 1});
  })
})

Upvotes: 2

Related Questions