Mocking HTTP requests is a vital part of any testing regiment. The ability to test a wide range of possible situations, realities and use cases is extremely important, and it presents a great opportunity to really future proof your API. What tool you use to implement this does matter — your tool should be able to mock common API interactions and HTTP request flows, and most importantly, it should be appropriate to your given code base and situation. These tools each offer something a little different from the others and present a variety of interesting build options and implementations.
Functionally, Nock does this by overriding both the http. ClientRequest functions, intercepting requests and responding with a specific mocked response through the use of Interceptors. Interceptors are addressed in the order they appear on a list, meaning that you can create multiple interceptors that result in different responses to two or more calls. It should also be noted that request paths can be a string, a filter function, or a RegExp.
This means you can use any HTTP verb to mimic a request across a multiplicity of different request paths depending upon your testing case with high complexity and variability. MockServer and its counterpart service MockServer Proxy is a multifaceted tool that comes in a variety of builds. For this reason, MockServer is both well-defined and configurable, making it a great option for most use cases. Beeceptor is a great tool largely because it requires absolutely no code in order to utilize it.
You can customize your responses to simulate pretty much any response or failure situation. Beeceptor also offers some great functionality to simulate latency on downstream APIs — you can both simulate transmit latency and timeouts, which is a great use case for many APIs and often missed during testing. This is another use case that is often missed by other mocking options, or if it is supported, it requires redeployment or ad hoc testing configurations.
Aside from its novel deployment method, Mockoon offers a wide range of support for common server variables. Self-signed certificates, rules-triggered responses, latency simulation, and more function to replicate common server conditions while allowing flexible enough configuration options to mock almost any system. Mocky is an incredibly simple and super lightweight testing implementation. Mocky is entirely a web app, meaning that everything is generated and managed remotely.
This does mean that Mocky grants you significantly less control compared to solutions that focus more on local systems, but this also means the application is simpler and cleaner. Mocky has great support for a ton of common functionality, but because it is a web app, you have to add this functionality in URL form.
For instance, adding? This sort of functionality still delivers quite a lot of value, but it does point to the relative simplicity of the app — if exceeding granular control is something that is desired, Mocky might not be the first option. For simple interactions, however, Mocky is a great choice.
Mockable was designed from the ground up to be simple and easy to use, and it shows — everything Mockable does and presents is slick and intuitive. One thing to note is that Mockable seems to have bought it on get value from object react native idea of offering the solution at hand primarily to enterprise users. Stoplight is all about the quick creation of mock servers and visualization of the APIs that interact with them.
Through a variety of tools, Stoplight offers excellent virtualization, automatic validation against OpenAPI documentation, and high support for configurable and dynamic content generation. Stoplight is also built upon Prisman open-source HTTP mock server offering — being open source is a huge benefit, and the fact that it also supports Swagger is definitely another pro.
It should also be mentioned that Stoplight is really a series of offerings rather that a singular option.Getting Multiple Requests
For enterprise users, Stoplight Hubs is a deployable documentation hub for custom branded documentation, and Stoplight Enterprise is its standard offerings beefed up for enterprise implementation. Mock Servers in Postman are tied directly to the Postman app, and for that reason, are a suggestion for a very particular use case.
That may not be a deal-breaker, of course — Postman is an excellent testing system and is in relatively common use by many API developers. Still, the fact that the mocking system is but a single aspect of a much larger testing apparatus may deter some users.
Mocklab takes this a step further, offering mocking through a web UI. Perhaps the two strongest value propositions for Wiremock is its request matching and traffic capture.
Execute multiple requests using the Organization service
This, paired with the relatively robust record and playback functions that allow traffic capture and analysis means that mock testing can be done pretty robustly. Mockserver is a library that utilizes mock files in order to serve realistic mock responses.When dealing with code that depends on external services maintaining test coverage and writing reliable tests can be challenging. Tests that make real HTTP requests to external services can be error-prone for a variety of reasons.
Examples include the exact data returned changing on each request, network connectivity problems, or even rate limiting. Intercepting and controlling the behaviour of external HTTP requests returns reliability to our tests. This is where Nock comes in. Nock can be used to test modules that perform HTTP requests in isolation. Also, it overrides http.
ClientRequest too to cover for modules that use it directly. Using canned data does come with risks, as it can go stale if not refreshed periodically.
Without specific additional tests, or pinned API versioning, this could mean that a change in the shape of the data an API returned would not be caught.
An example from my current employer is seen in our end-to-end tests. These use Nock fixtures, as when run during our continuous delivery pipeline they would occasionally suffer from timeout failures.
However, each time a developer runs these tests locally the fixtures are automatically deleted and regenerated, keeping them up to date. Nock is currently used in two main ways:. Either can be within individual tests. If both are used within the same test file then currently the nock. We will look at this in detail later. We will be building this example project. It contains some simplistic functions that call a random user generator APIperfect for testing out Nock.
It uses Jest as its test runner and for assertions. Three functions exist in the example to be tested: getting a random user, getting a random user of a set nationality, and getting a random user but falling back to default values if unsuccessful.
One example:. As we are using nock. The Nock docs explain this pretty well. Many options are available to specify the alteration of the request, whether in the request matched or the response returned. In the first test we use a string to match the hostname and pathand then specify a reply code and body.Writing tests can be a very important part of your development cycle.
Most code is easy to test, data goes in, write tests to make sure the right data comes out. Things start to get difficult when you introduce network requests. Getting started with nock is easy, all we need to do is add it to our project. The nock object itself will receive a hostname and then we can chain the request method.
When chaining the request method, we need to pass-in the URI of the endpoint as the first argument and optionally, the request body after that. The last thing we need is to chain the mocked reply from the server. Before executing code that will make a network request that we want to test, we have to setup a mocked network request that will be used in place of the network request in your code:.
The nock above will return successfully OK and return a payload that mimics the data that is returned by httpbin. All without actually making the external network request! Internally, nock keeps a list of these interceptors and as they are used, they are removed from the list.
The interceptors are used in the order they are created and we can define multiple interceptors that go to the same hostname and URI, but return different payloads. Because interceptors are removed after they are used, any time we want to test a network call, we have to make sure that we have an interceptor available. This shortcoming usually leads to writing a bunch of happy path tests that give no indication as to how well the system will respond to network failures or errors.
Getting Started Getting started with nock is easy, all we need to do is add it to our project. Tweet It.For example, a client might want to compose a view of unrelated data such as:. Combining these three individual requests into a single batch request can save the application significant network latency.
First you construct the JSON batch request for the previous example. In this scenario, the individual requests are not interdependent in any way and therefore can be placed into the batch request in any order. Responses to the batched requests might appear in a different order. The id property can be used to correlate individual requests and responses. The requests property is an array of individual requests. For each individual request, the idmethodand url properties are required.
The id property functions primarily as a correlation value to associate individual responses with requests. This allows the server to process requests in the batch in the most efficient order. The method and url properties are exactly what you would see at the start of any given HTTP request. Individual requests can optionally also contain a headers property and a body property. Both of these properties are typically JSON objects, as shown in the previous example.
When a body is included with the request, the headers object must contain a value for Content-Type. The response format for JSON batch requests is similar to the request format.
The following are the key differences:. The status code on a batch response is typically or If the batch request itself is malformed, the status code is If the batch request is parseable, the status code is A status code on the batch response does not indicate that the individual requests inside the batch succeeded.
This is why each individual response in the responses property has a status code. In addition to the responses property, there might be a nextLink property in the batch response. This allows Microsoft Graph to return a batch response as soon as any of the individual requests has completed. To ensure that all individual responses have been received, continue to follow the nextLink as long as it exists. Individual requests can be executed in a specified order by using the dependsOn property.
This property is an array of strings that reference the id of a different individual request. For this reason, the values for id must be unique. For example, in the following request, the client is specifying that requests 1 and 3 should be run first, then request 2, then request 4. If an individual request fails, any request that depends on that request fails with status code Failed Dependency. You can use JSON batching as a workaround for running these requests because the lengthy URL simply becomes part of the request payload.
For a list of current limitations related to batching, see known issues. Note that this specification is currently in a draft version, but is not expected to change. You may also leave feedback directly on GitHub.More often than not, an external resource may require authentication, authorization or may have a rate limiting.
Hitting an endpoint for a service hosted in a service like AWS as part of testing would also incur extra charges. This quickly goes out of hand when you are running tests a couple of times a day as a team, as well as part of continous integration. To get started, create a simple Node. Our tests will live inside a test directory, Go ahead and create a test directory and create our first test.
We are instead going to add it as an npm script. At this point, running npm test on your command-line should give you the following result. We obviously don't have any tests making requests, or a useful request for that matter, but we will be changing that.
Go ahead and create an index. Our test will assert that the request made returns an object with specific details. Replace the truthy test we created earlier with the following test for our code. This should pass on running the test by actually making a request to the Github API. Let's fix this! Nock works by overriding Node's http. Also, it overrides http. ClientRequest too to cover for modules that use it directly.
The whole idea behind this is that we are not testing the Github API, we are testing our own application. For this reason, we make the assumption that the Github API's response is predictable.
To mock the request, we will import nock into our test and add the request and expected response in the beforeEach method. To test that this is the actual response expected in the test, try editing one of the fields in the response object and run the test again. The tests should fail.
Nock v. State
In my case, I will be changing the name value to Scotch. You should get the error below. We have only scratched the surface on what you can do with nock. It has a very detailed documentation on how to use it and it is worth exploring.Let's deep dive into how mock servers and examples work together, and how you can integrate them into your workflow for an enhanced API experience with Postman.
The resulting response can be seen on the right, and a record of this request will now be visible in your history on the left. Collections are simply groups of requests that can be connected together to create APIs and workflows.
You can save a request to an existing collection, or save it to a new collection. Create a new collection called C1. Collection C1 will now be accessible in the Collections tab in the application. You can do all sorts of things within the collection details view: viewing API documentationmocking a collectionmonitoring a collectionor running the collection. Now, let's save an example response from the request just sent by hitting the Save Response button.
This takes us to the Examples screen which can be used to save the request response as an example. Let's call this example P1. Enter a name for this example. The request method, URL, and status code are crucial in determining which responses will be returned by the mock you will create.
Verify these elements are all as desired, and hit the Save Example button. Hit the back arrow in the top left to return to the request builder, and you can now see the example created in the top right, added to the request. In the previous steps, you prepared the collection, request, and example response necessary for us to get started with mocking.
There are two ways to create a mock for a collection: 1 using the Postman app and 2 using the Postman API. In this example, you will mock a collection using the Postman app. Here, you can choose a corresponding environment to include in your mock. The single saved example P1 does not use environment variables, so you can create a mock with No Environment chosen.
Mocks are accessible to public by default. If you check the box making the mock server private, you can share the underlying collection with the team or specific team members, and provide permissions to edit or view. Once you mock the collection, it will be visible under the Mocks tab of the collection details view. You can also see the mock URL you will need for the next step. Now that you have created the mock M1let's try sending a request to this mock endpoint.
Sending a request to this mock endpoint with an undefined path returns an error. As you can see, there is no matching saved example with the path '' and the request method GET. Responses returned by the mock service are entirely dependent on your saved examples and the included URL and request method type.
To further illustrate how responses from the mock service are entirely dependent on your saved examples, let's try adding another example to this collection. The collection C1 now has two requests and two saved examples:. Your examples might vary depending on the URL endpoint, request method type, or status code. Alternatively, if you have saved examples with different response status codes, you can send an authenticated request to the mock endpoint along with the x-mock-response-code header specifying which integer response code your returned response should match.
These dynamic variables are resolved as part of the Mock Server response and are replaced with the dynamic data for the variable used. These are very useful to generate random data in your API mocks. You can then use for exploratory testing and writing rich, data-driven tests. When you call that Mock Server endpoint, you will see the response change to something like this:. See the Postman Sandbox page for full list of available random data dynamic variables.
Postman's Mock server functionality is enhanced to return different responses based on matching request query params.Nock works by overriding Node's http. Also, it overrides http. ClientRequest too to cover for modules that use it directly. The latest version of nock supports all currently maintained Node versions, see Node Release Schedule.
When you setup an interceptor for a URL and that interceptor is used, it is removed from the interceptor list. This means that you can intercept 2 or more calls to the same URL and return different things on each of them. It also means that you must setup one interceptor for each request you are going to have, otherwise nock will throw an error because that URL was not present in the interceptor list.
You can specify the request body to be matched as the second argument to the getpostput or delete specifications. There are five types of second argument allowed:. String : nock will exact match the stringified request body with the provided string. Buffer : nock will exact match the stringified request body with the provided buffer.
JSON object : nock will exact match the request body with the provided object. In order to increase flexibility, nock also supports RegExp as an attribute value for the keys:. Function : nock will evaluate the function providing the request body object as first argument. Return true if it should be considered a match:. In case you need to perform a partial matching on a complex, nested request body you should have a look at libraries like lodash.
Indeed, partial matching can be achieved as:. The encoding format matches with request module. Nock supports passing a function to query. The function determines if the actual query matches or not. A query string that is already URL encoded can be matched by passing the encodedQueryParams flag in the options when creating the Scope.
Instead of an object or a buffer you can also pass in a callback to be evaluated for the value of the response body:.