Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

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

    Josh MockJosh Mock
    mochaMocha
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss