WebdriverIO comes with built in support for modifying network responses that allows you to focus testing your frontend application without having to setup your backend or a mock server. You can define custom responses for web resources like REST API requests in your test and modify them dynamically.
Before you can modify any responses you have define a mock first. This mock is described by the resource url and can be filtered by the request method or headers. The resource supports glob expressions by minimatch:
Once you have defined a mock you can define custom responses for it. Those custom responses can be either an object to respond a JSON, a local file to respond with a custom fixture or a web resource to replace the response with a resource from the internet.
In order to mock API requests where you expect a JSON response all you need to do is to call
respond on the mock object with an arbitrary object you want to return, e.g.:
You can also modify the response headers as well as the status code by passing in some mock response params as follows:
If you want the mock not to call the backend at all, you can pass
false for the
It is recommend to store custom responses in fixture files so you can just require them in your test as follows:
You can also just replace a web resource with another web resource if your desired response is already hosted on the web. This works with individual page resources as well as with a webpage itself, e.g.:
If your mock response depends on the original resource response you can also dynamically modify the resource by passing in a function receives the original response as parameter and sets the mock based on the return value, e.g.:
Instead of returning a custom response you can also just abort the request with one of the following HTTP errors:
This is very useful if you want to block 3rd party script from your page that have a negative influence on your functional test. You can abort a mock by just calling
Every mock is automatically a spy that counts the amount of requests the browser made to that resource. If you don't apply a custom response or abort reason to the mock it continues with the default response you would normally receive. This allows you to check how many times the browser made the request, e.g. to a certain API endpoint.