mswjs / mswjs.io Goto Github PK
View Code? Open in Web Editor NEWOfficial website and documentation for the Mock Service Worker library.
Home Page: https://mswjs.io
Official website and documentation for the Mock Service Worker library.
Home Page: https://mswjs.io
Each MDX file has the order
frontmatter property that is used to sort all the MDX pages before building the pages tree.
order
property is global (11
, 24
, 55
), so regardless of the location of the file, it can be placed anywhere. This makes it hard to maintain (i.e. if a new section is added).order
property requires to update all the siblings, and pages listed after it (logically).We can have an explicit map representing pages (incl. hierarchy). When all MDX documents are queried, they are sorted against this map. Entries not found in the map are appended after the map is produced.
// docs/map.js
module.exports = [
{
title: 'Introduction',
url: '/'
},
{
title: 'Getting started',
url: '/getting-started'
pages: [
{ title: 'Install', url: '/install' }
]
}
]
The structure of the ordering tree is to be discussed.
Test content.
There is a section in the 1->2 migration guide that addresses the problem of tests in Jest not having access to the global objects such as Request
, Response
, TextEncoder
, fetch
, etc.
The proposed solution includes installing the undici
package, importing the missing fetch-related globals from it, and assigning them to Jest global.
I have come across a different solution for when the tests are run in jsdom environment. You may find it a bit simpler, in that it does not require any extra libraries. It assumes that you already have jest-environment-jsdom
package installed, which you probably do if you are running your jest tests in jsdom. Here is what it involves:
// my-jsdom-environment.js
const JSDOMEnvironment = require('jest-environment-jsdom').default; // or import JSDOMEnvironment from 'jest-environment-jsdom' if you are using ESM modules
class MyJSDOMEnvironment extends JSDOMEnvironment {
constructor(...args) {
super(...args);
// here, you have access to regular Node globals, which you can add to the test environment
this.global.Request = Request;
this.global.Response = Response;
this.global.fetch = fetch;
// ... and so on
// you might want to add some other missing globals, unrelated to fetch, such as structuredClone
this.global.structuredClone = structuredClone;
}
}
module.exports = MyJSDOMEnvironment;
module.exports = {
testEnvironment: './my-jsdom-environment',
};
Link from https://mswjs.io/docs/api/setup-server/use
page to 'Network Behaviour Overrides' broken.
Link should be:- https://mswjs.io/docs/best-practices/network-behavior-overrides/
If I get some guidance, I can help solve this issue, It is irritating for the left bar to also scroll to top when any menu option is clicked. I am familiar with basic reactJS.
It resolves relatively to the current origin.
It's an absolute link to GitHub.
The Setup section of the Browser integration page in the docs should link to the Service Worker API docs on MDN for people who would like to learn more about that API.
It seems it refers to the last commit date touching the page, which may not be accurate considering rebasing strategy.
The "Updated at" date should reference the date of the latest commit changing the file.
When opening https://mswjs.io some of the requests to Google Fonts result in HTTP 400:
Invoking one of these URLs directly leads to the following error page:
https://fonts.googleapis.com/css2?family=Source%20Code%20Pro:ital@0;2&display=swap
Not sure, but I think in Firefox (FF 81, MacOS) this leads to missing syntax highlighting:
(After removing 'Source Code Pro' from the styles the syntax highlighting works, so I think that might be related to the invalid requests)
Is your feature request related to a problem? Please describe.
For example, a command from the section: https://mswjs.io/docs/getting-started/integrate/browser#configure-worker:
$ touch src/mocks/browser.js
There is a copy button at the end of the command, it will copy the unnecessary character $
. That will make the command failed if you press enter without deleting $
character.
^ react-components [master] $ touch src/mocks/browser.js
zsh: command not found: $
Describe the solution you'd like
Put the $
character where it cannot be copied. Or make it as an icon.
I'm setting up MSW for GraphQL server. I got following error in console:
Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL
requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation
Though page https://mswjs.io/docs/api/graphql/operation doesn't exist.
Hi guys!
First of all, thanks for this amazing project which helps me a lot!
I found a typo in query-parameter page
In order to access a query parameter of the intercepted request, use the searchParams propery on the req.url instance
I think it should be "property" instead of "propery".
I would like to open a PR to fix the typo.
Thank you!
Hi 🔢
I want to know what is the execution logic for setupWorker function 👯
It is first router declaration to the end ( A > B > C) or (C > B > A).
Because i don't understand why my regex who catch all url of my server domain and return status 500 have the same comportement at the first position (A) and at the end position declaration (C). I have multiple mock status 200 declaration and i don't understand why when i put my regex of status 500 at the first position declaration i got the same comportment that when i declare it at the end
Thanks 👋
I was trying to follow this part of the guide
mswjs.io/docs/getting-started/integrate/browser.mdx
Lines 87 to 105 in 5b607af
And it's not clear if this should be done in addition or instead of the previous step (Using conditional import). Because with each of the options I have some issue:
worker.start()
webpackChunkName
:if (process.env.NODE_ENV === 'development') {
import(/* webpackChunkName: "api-mock" */ '@/api/mocks/browser')
.then(({ worker }) => worker.start());
}
I'm not too experienced with how webpack is supposed to work here, but I suppose I'm not the only one, so elaborating the docs could help also some other people out there.
Outcome of mswjs/msw#245.
To suggest a proper modules splitting as the default recommendation. That'd allow to reuse the same mock definition for both browser and server, without mixing the context (cannot call setupWorker
in Node, and vice versa in regards to setupServer
.
mocks/browser.js
and mocks/server.js
files in the respective integration pages.I think the document should have something like Things to notice when update msw
to a newer version. Since usually to update, people only do npm install --save-dev msw@{version|tag}
. If they are using msw
to work with the browser, they need to re-generate the mockServiceWorker.js
file by executing npx msw init <PUBLIC_DIR>
as well (in case there is any change).
In my case, I update msw
from 0.19.x
to 0.24.x
and it didn't work. It took me a while to figure out that I should update mockServiceWorker.js
as well. I think we should mention it in the docs to save other people's time.
@kettanaito
Reference: The difference of mockServiceWorker.js
between 0.19.x
and 0.24.x
https://www.diffchecker.com/11a1JE0u
It seems that rest.all
that was added with this pull request isn't mentioned in the documentation. Is this intentional?
Thanks
I was reading this page: https://mswjs.io/docs/basics/intercepting-requests
And my opinion is the font makes it a lot harder to read the comment
Page https://mswjs.io/docs/api/response
Was brought there by Google
Would be good to have
*.mdx
file should include its URL (file-system based public path) so when you reference a page using PageLink
component, you don't have to manually provide an error-prone url
prop:import * as SomePage from './page.mdx'
-<PageLink page={SomePath} url="/docs/long/path/page" />
+<PageLink page={SomePath} />
Such custom MDX loader may parse and include the following data in the module:
import { pageInfo: SomePageInfo } from './page.mdx'
<PageLink page={pageInfo} />
Congratulations on the new major release!
Could you please add a light version for the docs? Having a light/dark/system color scheme switcher would be nice. It’s not about the nice appearance but about accessibility.
I have trouble reading light text on a dark background. It strains my eyes a lot, and after some time reading, I see everything with a “zebra” effect :( It’s similar to when you look at the sun, and then you have a black spot in your vision. But with this, you have black lines in your vision.
People with dyslexia and astigmatism may have issues reading light text on dark backgrounds.
It would be nice for the Examples page to sync its examples with the Examples repository automatically. This can be achieved by:
When dealing with runtime requests to GitHub API one needs to take rate limiting into consideration.
For a new contributor it may be confusing how to get into the project. I suggest we add a "Get involved" link, or a page, that would describe how they can help.
There are multiple ways to help:
help wanted
and good first issue
issues in the MSW repo.I'm trying to migrate my jest tests from mocking axios to msw (something like what's suggested in https://kentcdodds.com/blog/stop-mocking-fetch). Mostly it works 🎉
Tests sometimes don't wait for api requests to be resolved. So the tests fail randomly (race condition).
The solution that worked when I was mocking axios is https://www.npmjs.com/package/flush-promises
Could the msw docs describe how to handle this?
Here's a nice article that goes into detail on how cy.route()
API works:
Should update our Comparison page to include a proper description of the cy.route()
internal implementation.
Cypress establishes a browser-wide network proxy that routes all traffic from the web page to the proxy server.
Expect to see a description of the printHandlers method of setupWorker;
Link is present at https://mswjs.io/docs/api/setup-worker
seems it should be listHandlers method instead?
should say graphql.mutation<Response, Variables>
instead of graphql.mutation<Variables, Response>
This page in the docs: https://mswjs.io/docs/getting-started/mocks/rest-api doesn't mention typescript - but the https://mswjs.io/ page has a TypeScript tab.
The getting started guide should provide examples in typescript as well, or a link to a getting started with TypeScript page.
Hi!
Is there a way to add "global" life-cycle events that would execute for all servers?
I think it would be really helpfull for those who use msw in tests and would like to be notified ie when there is an exception withing the msw mock code.
Thanks!
Getting Started > Integrate > Node talks about importing src/mocks/server.js
to stop and start the server, but the reader has not yet created that file. The Node section probably needs a step where that file is created, similar to the Configure Worker step in the browser integration section.
Hi, @kettanaito.
The documentation currently has only Cypress example, but we can do the same with Playwright.
Below code works fine as far as I've tried.
const url = (path) => `http://localhost:3000${path}`;
test.beforeEach(async ({ page }, testInfo) => {
await page.goto(url("/login"));
await page.evaluate(() => {
const { worker, rest } = window.msw;
worker.use(
rest.post(url("/login"), (req, res, ctx) => {
return res(ctx.json({ success: true }));
})
);
});
});
test("handles user authentication", async ({ page }) => {
// Describe application interactions for this test.
});
Please consider whether it can be posted as a usage example.
The example https://mswjs.io/docs/best-practices/custom-request-predicate#request-body-predicate will throw a type error in typescript even after adding proper types to it. One can check it at https://github.com/kulla/2023-11-14-msw-examples/blob/main/src/with-json-body.ts by running npm run test
in this project.
Let's take the following example:
import { ResponseResolver } from 'msw'
function simplePredicate(resolver: ResponseResolver): ResponseResolver {
return async (args) => resolver(args)
}
The return type of resolver(args)
has the form OtherTypes | Promise<PromiseTypes> | Generator<GeneratorTypes>
due to the current type definition of a ResponseResolver
. Therefore async (args) => resolver(args)
has the return type Promise<OtherTypes | Promise<PromiseTypes> | Generator<GeneratorTypes>>
so it might be a promise of a generator.
This does not match the return type of ResponseResolver
. It include promises, however in the current definition PromiseTypes
cannot be a generator.
At https://github.com/kulla/2023-11-14-msw-examples/blob/main/src/with-json-body.ts I have added some examples. By running npm run test
one can see the type error in https://github.com/kulla/2023-11-14-msw-examples/blob/807e3036e3404c49dbb6ab7dda9596e2a2db0bb8/src/with-json-body.ts#L16.
I have added two examples how one can make typescript happy. It shows that the generator type is the reason for the type error.
In the following section, bypass is described only as B.
https://mswjs.io/docs/api/setup-server/listen/#onunhandledrequest
Need to add the "Examples" page to the website.
Current "Examples" link in the header points to the GitHub repository. I think it would be much more appealing and easier to navigate through examples if we introduce some UI.
src/pages/examples.tsx
.h2
elements).src/components/header.tsx
to point to the local page (/examples
).Awesome feature, needs documentation.
See the warning line in a custom strategy example for onUnhandledRequest
server.listen({
onUnhandledRequest(request) {
console.log('Unhandled %s %s', request.method, request.url.href)
},
})
However, since request
is of type Request
, request.url
is a string; and request.url.href
does not exist.
Right now to fetch a page's contributors the runtime makes a call to GitHub API V3 to get the authors of the page. This is not good, because:
First of all, thank you @kettanaito and rest of the contributors for the msw
library and this amazing documentation 👏
In some of my projects I have a dev environment that relies on webpack-dev-server, that happens to not have a predefined "public" directory.
The easiest way I found to make it work for me was to use CopyWebpackPlugin to get the Mock Service Worker file into the served content, as follows:
// webpack.config.js
const { SERVICE_WORKER_BUILD_PATH } = require('msw/config/constants');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
...
plugins: [
new CopyPlugin({
patterns: [{ from: SERVICE_WORKER_BUILD_PATH }],
}),
],
...
}
A nice bi-product of doing it this way is that the Mock Service Worker file is always up to date throughout eventual msw
version bumps.
Since I found this useful for me, I was thinking about adding this to the documentation as an alternative way to the init method.
First I'd like to know if you think that this is a proper way of bringing in the Mock Service Worker file, and also whether it makes sense to mention it in some way in the official docs.
In case it makes sense, I was thinking about where it should be placed. IMO, it could probably live on its own as a Recipe and as secondary/alternative way to Setup.
Let me know what you think!
I am an msw
user for a couple of years. I used to use msw like this:
rest.post("*/api/project-readme", (req, res, ctx) => {
...
});
I know that msw
recently support baseUrl
, so I don't need to mock */...
anymore. So I head to https://mswjs.io/docs/ to see how I can configure that. But the documentation site currently does not have a search function. So it's very difficult for me to locate the docs and know how to do it. I might end up mocking */...
.
cc: @kettanaito
The TODO for this PR is not done yet. Is it okay to contribute for this documentation?
Content jumps are occurring on many pages due to the bug in "atomic-layout" dependency. This issue affects any component that utilizes "makeResponsive" or "useResponsiveProps" directly. I'm opening an issue here to increase its visibility. For more information, please refer to this issue.
Currently, only the number
option is documented. "real"
and "infinite"
are not.
Refreshing the page fixes the issue.
I thought this had to do with the introduction of <ViewTransition />
from Astro but removing it does not fix the issue. Looks like some fixed invisible element stays on the page, eating the scroll.
See the manifest file and inspect 256px+ icons. Since they are generated by 32x32 icon source, they have a poor quality.
Ideally, use explicit icons for each size, since MSW's logo shouldn't be scaled (loses proportion and border width).
TypeError: Protocol "http:" not supported. Expected "https:"TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:"
Here is an error message I while trying to integrate my mocks with react testing library and jest. Our app is CRA. We're also using react-router-dom, and our component is tied to the route
import React from 'react';
import { ApolloProvider } from '@apollo/client';
import { MemoryRouter as Router, Route } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import apollo from './apolloClient';
import ProjectHeader from './ProjectHeader';
it('has a test', async () => {
const { container } = render(
<ApolloProvider client={apollo}>
<Router initialEntries={['/project/1']}>
<Route path='/project/:projectId'>
<ProjectHeader />
</Route>
</Router>
</ApolloProvider>,
{}
);
I noticed that there is documentation about the need for an absolute path, and example for a rest api. Is there any documentation on what should I do for a graph api?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.