Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    Josh MockJosh Mock

    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.



    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




    Instructor: 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.

    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.

    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.

    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.