This Week I Learned About Sinon Matchers

I'm a huge fan of Sinon for test spies, stubs, fake timers, etc – but I continually learn new things about it. This week I learned about sinon matchers.

While some of us were pairing on a test case at LeanKit this week, we needed to verify part of an object passed into a method we were stubbing.

Previously, if we had to test something like this, we'd use the args on the stub:

var stub = sinon.stub();
stub( "topicName", { other: "field", some: "object" } );

// In the test
stub.lastCall.args[0].should.equal( "topicName" );
stub.lastCall.args[1].some.should.equal( "object" );

It is much nicer to write using sinon's calledWith method, but this would fail since we are doing a partial match:

// this test fails "topicName", { some: "object" } );

(We use chai and its should syntax with sinon-chai to achieve this syntax.)

However, now with sinon matchers, we can write the following and it will match the partial object: "topicName", sinon.match( { some: "object" } ) );

You can use regexp, string and other matchers as well including a custom function matcher and nested matchers. I can't wait to use these more in our tests going forward.

News Films

Our little film studio focuses on telling developer-centric stories that need to be seen.

GopherCon 2016 Conference Recap

0:00 / 0:00