Comments (5)
Hey, @amit08255. Thanks for reaching out.
Although you can use node-request-interceptor
directly, I highly recommend you adopt the setupServer
API from MSW. MSW (Mock Service Worker) is an API mocking library that uses node-request-interceptor
to power its NodeJS requests interception. However, on top of that it adds the same API that would allow you to reuse request handlers in other levels of testing (i.e. E2E) and for development in a browser as well.
Would the setupServer
satisfy your requirements? Let me know if there is more context to this question.
from interceptors.
@kettanaito Please can you provide an example of using node-request-interceptor directly. It would be very very helpful.
from interceptors.
Sure. Here's an example how you can use it with Jest directly.
import { RequestInterceptor } from 'node-request-interceptor'
import fetch from 'node-fetch'
// Start requests interception.
const interceptor = new RequestInterceptor()
beforeAll(() => {
// Declare how to react to each intercepted request
// using a request middleware function.
interceptor.use((req) => {
if (req.url.href === 'https://api.github.com/numbers') {
return {
status: 200,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify([1, 2, 3])
}
}
})
})
afterAll(() => {
// Restore patched modules and stop requests interception.
interceptor.restore()
})
test('returns the list of numbers', async () => {
// Perform a request to any endpoint that is handled
// in the request middleware above.
const res = await fetch('https://api.github.com/numbers')
const body = await res.json()
expect(body).toEqual([1, 2, 3])
})
Also check out this repository's README, it lists all the API and examples.
I still don't recommend it, because there is much to add in order for such interception to be comfortable. For example:
- You have to provide request matching logic manually, NRI will not do this for you as this is out if its scope.
- Account on query parameters and hashes in request URL.
- Assigning headers and body is quite verbose, you need to construct a valid response manually (i.e. don't forget about proper
Content-Type
header). - NRI, as the name implies, does not work in a browser.
The main argument is that the application scope of NRI is intentionally low-level. While this intercepts requests and allows to mock their responses, there's quite a lot one needs to add to this to be applicable in an actual project. This is what MSW does on top of NRI to ensure consistent user experience.
May I wonder why do you wish to use NRI directly? Do you have any reason not to use MSW?
from interceptors.
@kettanaito I am still a beginner with testing. I am designing a ReactJS app with test-driven development. For that I need to test my app without making real request and need to test if data sent to API is correct. Please help me with that, if possible with example. It will help me a lot.
from interceptors.
I suggest you follow the Getting started tutorial on MSW website. It will explain you the concepts you need to achieve proper API mocking layer integration, and give you examples of browser/NodeJS usages along the way. Reading the documentation in general is what I would recommend as a good start.
Next, take a look at the official usage examples in MSW. Those contain real-world applications with libraries like React, Angular, as well as different API types (REST, GraphQL). You can draw some inspiration there and use them as a reference in your project.
When in doubt, take a look how MSW is integrated in the Bookshelf app that is used for the video series on application testing.
Lastly, in case of any questions we will be happy to help you in KCD discord in the msw
channel. Hope that you achieve an awesome testing setup.
from interceptors.
Related Issues (20)
- WebSocket: Outgoing client events have the wrong "currentTarget" HOT 2
- WebSocket: Decide how to handle actual server errors
- Flaky: `modules/http/response/readable-stream.test.ts`
- ClientRequestInterceptor incorrectly encodes basic authentication header HOT 15
- Abstract request emitting logic HOT 1
- Await all "response" listeners to finish HOT 6
- Protocol "https:" not supported. Expected "http:" when using "proxy-agent" HOT 1
- Simplify the npm package files HOT 3
- XMLHttpRequest upload (upload.onprogress) event is not supported HOT 4
- Issue with native fetch introduce after 0.25.1? HOT 3
- Nock compatibility HOT 2
- Unclear how to throw an actual error HOT 3
- Proper documentation on how to use it HOT 1
- RemoteHttpResolver example in README is missing the ".apply()" call HOT 2
- `@mswjs/[email protected]` breaks `URL` as fetch argument
- should pass filteringPath options HOT 1
- ERR_MODULE_NOT_FOUND Cannot find module HOT 1
- Support reusing the same Socket for multiple requests HOT 1
- Cannot find module '@mswjs/interceptors/presets/browser' or its corresponding type declarations.
- Support Response.error() in RemoteInterceptor
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from interceptors.