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

    Mock an HTTP request using Nock while unit testing

    Josh MockJosh Mock

    When testing functions that make HTTP requests, it's not preferable for those requests to actually run. Using the nock JavaScript library, we can mock out HTTP requests so that they don't actually happen, control the responses from those requests, and assert when requests are made.

    mochaMocha
    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 When unit testing a function that makes an HTTP request, it can be helpful to mock out the HTTP request to ensure that it doesn't happen and also to verify what is happening during that request.

    00:11 To mock out a request, we can use the nock function, passing it the schema and the host name of the request that's being made. We can then call its .get function, because that's the kind of HTTP request we're making, and pass it the path name of the request.

    00:27 Then we can mock a response by using the reply function. We'll give it a 200 response and pass back an array of users. Now we can call our function and be sure that a real HTTP request won't happen.

    00:39 We can also verify that the mock response that we created is what's actually being returned. We can check that the response's value is equal to the array of user names. We can also assign the output of nock to a variable and use that to assert that the mock request was called.

    01:01 Let's see if our unit test passed. As you can see, we were able to mock our request using nock, give it a response that we wanted, verify that that was the response that we got, and also verify that our mock request was called.

    Discuss

    Discuss