⚠️ 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.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today