GithubHelp home page GithubHelp logo

mswjs / mswjs.io Goto Github PK

View Code? Open in Web Editor NEW
147.0 147.0 169.0 6.51 MB

Official website and documentation for the Mock Service Worker library.

Home Page: https://mswjs.io

JavaScript 0.42% TypeScript 67.74% CSS 0.50% Astro 4.09% MDX 27.24%
api match mock mocking msw request routing service-worker

mswjs.io's People

Contributors

aganglada avatar buob avatar dandelionadia avatar dependabot[bot] avatar epreston avatar hajime-san avatar izhaki avatar john-james-gh avatar juhanakristian avatar kettanaito avatar ledenis avatar m98 avatar marcobiedermann avatar marcosvega91 avatar martinhecher avatar mashabow avatar michaeldeboey avatar michieltondeur avatar mspangler avatar murilobr avatar mustafahaddara avatar olingard avatar reslear avatar sairus2k avatar slaweet avatar thomasmery avatar timdeschryver avatar willnguyen1312 avatar wkovacs64 avatar zoltan-nz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

mswjs.io's Issues

Improve docs page ordering

Current implementation

Each MDX file has the order frontmatter property that is used to sort all the MDX pages before building the pages tree.

Issue

  • the 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).
  • change in the order property requires to update all the siblings, and pages listed after it (logically).

Suggested solution

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.

Alternative Jest setup for when Request/Response/TextEncoder is not defined

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:

  1. Create a file that customizes the jsdom environment:
// 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;
  1. Update jest config to point to your new file for test environment:
module.exports = {
  testEnvironment: './my-jsdom-environment',
};

Docs | minor issue with an unactive link

Hi,
The link in the API > http section of the Docs sidebar does not become active or highlighted when we are on the page in question.

This is something I've noticed while working on implementing light mode for the website.

Screenshot of the issue

image

Expected result
image

Broken link in doco

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/

"Updated at" date below the docs page is incorrect

It seems it refers to the last commit date touching the page, which may not be accurate considering rebasing strategy.

Expected behavior

The "Updated at" date should reference the date of the latest commit changing the file.

Invalid Google Fonts URL

When opening https://mswjs.io some of the requests to Google Fonts result in HTTP 400:

grafik

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

grafik

Not sure, but I think in Firefox (FF 81, MacOS) this leads to missing syntax highlighting:

grafik

(After removing 'Source Code Pro' from the styles the syntax highlighting works, so I think that might be related to the invalid requests)

Remove '$' character from the command in official docs.

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.

Typo "propery"

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!

setupWorker Function, order of execution ?

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 👋

"Using webpack" section of "getting started" not clear

I was trying to follow this part of the guide

### Using webpack
If you can access your build configuration, consider importing the mock definition as a conditional entry module. This is the best strategy for your application to know nothing about the mocking.
```js showLineNumbers focusedLines=6-7
// webpack.config.js
const __DEV__ = process.env.NODE_ENV === 'development'
module.exports = {
entry: [
// Conditionally include the mock definition file
__DEV__ && 'src/mocks/browser.js',
// Include your application's entry
'src/index.js',
].filter(Boolean),
// The rest of your webpack config...
}
```
https://mswjs.io/docs/getting-started/integrate/browser#using-webpack

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:

  • If "Using webpack" section is instead of, "Using conditional import", then I don't understand how/where to call an equivalent of worker.start()
  • If it's in addition, then I wonder if it could be achieved just with 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.

Getting started: Use separate browser/server modules for the Integration part

Outcome of mswjs/msw#245.

Why

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.

How

  1. Mention to create separate mocks/browser.js and mocks/server.js files in the respective integration pages.

Things to notice when update `msw` to a newer version

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

Write custom MDX loader

Public path

  • Each *.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:

  • Page URL
  • Page title (from frontmatter)
  • Possibly refine how the information it exported, so you don't have to import everything from a module:
import { pageInfo: SomePageInfo } from './page.mdx'

<PageLink page={pageInfo} />

Add light theme to the docs

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.

Sync examples with the example repository

It would be nice for the Examples page to sync its examples with the Examples repository automatically. This can be achieved by:

  • Unifying the structure and metadata of an example to include name, description, and an icon reference.
  • Fetching the list of examples either on page's runtime, or during build-time (makes it out-of-sync).

When dealing with runtime requests to GitHub API one needs to take rate limiting into consideration.

Adds "Get involved" link/page

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:

  1. Review and edit the documentation.
  2. Get started with the help wanted and good first issue issues in the MSW repo.
  3. Generally describe what libraries are used, what is their relation, so people may find a field they are most interested in.

global life-cycle events handlers

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!

Examples of Permanent override for Playwright

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.

TypeScript error when using async resolver predicates

Bug description

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.

Reason for the bug

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.

Examples

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.

Adds the "Examples" page

What

Need to add the "Examples" page to the website.

Why

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.

How

  1. Create src/pages/examples.tsx.
  2. Add two sections to the Examples page: "API types" and "Libraries & Frameworks" (both can be h2 elements).
  3. Create a box component that represents a single example. Each example box should have a logo of the technology, the name of the technology, and a short description about the example.
  4. Each example box is a link, which, when clicked, leads you to the respective example folder in the Examples repository. For example, if I click on the "GraphQL example", it should link me to this folder.
  5. Update the "Examples" link in the src/components/header.tsx to point to the local page (/examples).

Feedback: Using local HTTPS

Discussed in #322

Originally posted by Cedoriku November 27, 2023

Feedback

The flags listed are not existing anymore on Chrome. Doc is outdated. Result is I can't use MSW with my local https relied development environment

Page contributors should be extracted on build time

What

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:

  1. The visitor of the page needs to have a GitHub account to communicate with GitHub API.
  2. The calls are subjected to GitHub's standard rate limiting policy. After N amount of calls the list of contributors won't load at all.

How

  1. Extract contributors once at build time.
  2. Cache results of the first GitHub API call for file's authors and never request them again.

Docs contribution idea: Alternative way of placing the Service Worker file with webpack

First of all, thank you @kettanaito and rest of the contributors for the msw library and this amazing documentation 👏

Motivation

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.

How can I contribute?

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!

Add a full-text search feature

Motivation/ Personas

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 */....

Suggestion

Reference

cc: @kettanaito

Content "jump"

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.

Site is unscrollable after mobile navigation

Steps to reproduce

  1. Open mswjs.io.
  2. Click on the mobile nav icon.
  3. Navigate to any page (Docs/Blog).
  4. The page cannot scroll.

Refreshing the page fixes the issue.

Initial guess

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.

Bigger favicons quality is poor

See the manifest file and inspect 256px+ icons. Since they are generated by 32x32 icon source, they have a poor quality.

Solution

Ideally, use explicit icons for each size, since MSW's logo shouldn't be scaled (loses proportion and border width).

How to integrate Direct Usage with Graph API

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.