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

Mock an HTTP request using Nock while unit testing

Josh Mock
InstructorJosh Mock
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 2 years ago

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.

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.

egghead
egghead
~ 9 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