Aamer Rasheed
Aamer Rasheed

Reputation: 155

How to match some values of object using sinon stub

I've been writing test using sinon. During the same I wrote stub where some input parameters are passed and an object is returned. This object returns some values and a random date value generated by system at the time of execution. So need guidance on following.

  1. How can I handle the same as the matching arguments are static in nature and I don't know the possible value of the date generated by actual code.
  2. How can we skip certain key values of an object using sinon. i.e. say object has following values. const object = {name: "abc", employeeNumber : "123"} I only want to check if name is "abc" and don't need to match employeeNumber.

Upvotes: 3

Views: 12013

Answers (2)

joshuakcockrell
joshuakcockrell

Reputation: 6113

Use sinon.match(..) or sinon.match.any

class CarManager {
  static drive(car, km) {
    console.log(`You drove a ${car.color} ${car.make} ${km} km.`);
  }
}

test('partial object match', () => {
  var spy = sinon.spy(CarManager, "driveCar");
  
  CarManager.drive({ make: "BMW", color: "red" }, 20);
  CarManager.drive({ make: "Porsche", color: "black" }, 10);

  // Accepts any type of BMW
  assert(spy.calledWith(sinon.match({ make: "BMW" }), sinon.match.any));

  // Accepts any type of black car
  assert(spy.calledWith(sinon.match({ color: "black" }), sinon.match.any));

  // Accepts any 1st argument, requires specific km
  assert(spy.calledWith(sinon.match.any, 20));
})

Upvotes: 1

Brian Adams
Brian Adams

Reputation: 45810

From the sinon.match docs:

Requires the value to be not null or undefined and have at least the same properties as expectation.


From the sinon.assert.match docs:

Uses sinon.match to test if the arguments can be considered a match.


Example:

test('partial object match', () => {
  const object = { name: "abc", employeeNumber : "123" };
  sinon.assert.match(object, { name: 'abc' });  // SUCCESS
})

Upvotes: 3

Related Questions