⚠️ This lesson is retired and might contain outdated information.

Unit Test a Function that Invokes a Callback with a Sinon Spy

Josh Mock
InstructorJosh Mock
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 2 years ago

Unit testing functions that invoke callbacks can require a lot of setup code. Using sinon.spy to create a fake callback function can simplify your unit tests while still allowing you to observe the output of the function you're testing.

Instructor: [00:00] To unit test a function that calls a callback when it's finished, we can use a sign-on spy. A sign-on spy is a function that doesn't do anything except keep track of when it's been called. Let's create a sign-on spy instance.

[00:13] We can call our function and pass a spy instead of a normal callback function. Now, we can assert that the spy's call count is one to verify that the getTempFile's callback was called exactly one time. Let's see if our test passed.

[00:27] The call count equals one, because our spy has been called exactly one time. We can also use the spy's getCall function to get a call's arguments, and then check that it's the right data type using the instance of keyword.

[00:41] Our unit test is still passing. As you can see, we were able to count how many times our spy was called as a callback, and what arguments were passed to it when we call the function that we're unit testing with our sign-on spy.