Giter Site home page Giter Site logo

examples's Introduction

Examples

A collection of usage examples of Mock Service Worker.

JavaScript frameworks

  • Angular (Jest, Cypress)
  • Next.js
  • React Native
  • Remix (Playwright)
  • SolidJS
  • Svelte (Vitest, Playwright)
  • Vue (Vitest, Cypress)

Test frameworks

Other tools

  • Storybook

Reading examples

Each example is a standalone repository featuring the usage of MSW with a certain framework or tool. Follow the instructions written in the README.md of respective examples to integrate MSW with those particular technologies. Some examples have separate instructions for client-side and server-side integrations. You can choose either or both, depending on where you wish to gain control over the network with MSW. We highly recommend implementing both client-side and server-side interception to guarantee seamless development and testing experience.

Cloning examples

Each example can be forked immediately with CodeSandbox. To do so, click on the "Edit on CodeSandbox" button in the README.md of the respective example. This will load it in the cloud, allowing you to experiment with the integration and create reproduction cases easier.

Edit in CodeSandbox example

examples's People

Contributors

jefiozie avatar juhanakristian avatar kettanaito avatar luistak avatar marcosvega91 avatar monicag avatar prscoelho avatar puglyfe avatar sapegin avatar serkansipahi avatar skvale avatar timdeschryver avatar trivikr avatar vantanev avatar willnguyen1312 avatar wkovacs64 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

examples's Issues

MSW with GrapqhQl fragments

Hey, could you please guide me with the graphql query that is using fragments. Without fragments graphql queries are working fine and Mock Service Worker is serving results as expected.

But this one query is not using msw and is still making request to the actual api.

query FeaturesQuery($site: String!) {
  features {
    ...FeaturesFragment
  }
}

fragment FeaturesFragment on Features {
  __typename
  id
  automaticFeaturedEventsEnabled: isFlagActive(site: $site, name: "automaticFeaturedEvents")
  is2MeeEnabled: isFlagActive(site: $site, name: "is2MeeEnabled")
}

In msw handlers I've defined just

export const handlers = [
  graphql.query('FeaturesQuery', (_req, res, ctx) =>
    res(
      ctx.data({
        features: {
          __typename: 'Features',
          id: 'RmVhdHVyZXM6R0xPQkFMTFlfVU5JUVVFX0ZFQVRVUkVTX0lE',
          automaticFeaturedEventsEnabled: true,
          is2MeeEnabled: true,
        },
      })
    )
  ),
];

How should I tweak the query so that msw would understand it?

Set multiple "msw.workerDirectory" in root-level package.json

The new version of MSW supports a list of worker script directories in msw.workerDirectory. We can utilize that to ease the upgrade path and to generate the worker scripts at multiple examples at the same time while running npx msw init from the root of the repo.

Not intercepting Apollo GQL requests at all

Hi! i just want to say that i read all issues with that title and browse through all internet and can't make it work.

Apollo client version: 3.7.4
msw version: 0.49.3

My setup test file:

import { cleanup } from '@testing-library/react';
import { afterEach, beforeAll, afterAll } from 'vitest';
import matchers from '@testing-library/jest-dom/matchers';
import { expect } from 'vitest';
import { server } from './mocks/server';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
HTMLCanvasElement.prototype.getContext = () => ({} as any);

beforeAll(() => {
  server.listen({
    onUnhandledRequest: 'warn',
  });
  server.printHandlers();
});

afterEach(() => {
  cleanup();
  server.resetHandlers();
});

afterAll(() => server.close());

expect.extend(matchers);

My server

// src/mocks/server.js
import { setupServer } from 'msw/node';
import { graphQLHandlers } from './graphQLHandlers';
import { restHandlers } from './restHandlers';
// This configures a request mocking server with the given request handlers.
export const server = setupServer(...graphQLHandlers);

Query: generated by code gen

export const WatchlistDocument = gql`
  query Watchlist {
    watchlist {
      id
      venueAccount
      securityId
      symbol
    }
  }
`;

My client setup

const httpLink = new HttpLink({
  uri: `${import.meta.env.VITE_REST_API_SERVER}/graphql`,
});


export const apolloClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: httpLink,
});

finally my handlers:

import { graphql } from 'msw';

export const graphQLHandlers = [
  graphql.query('Watchlist', (req, res, ctx) => {
   //It is never called
    console.log('querinasdas dasd asd asd asd asd asd asd asd asd asd g!!');
    return res(
      ctx.data({
        watchlist: [
          {
            __typename: 'WatchlistResponse',
            id: '1',
            symbol: 'SHIBUSD',
            venueAccount: 'Bitfinex',
            securityId: '1',
          },
          {
            __typename: 'WatchlistResponse',
            id: '2',
            symbol: 'SHIBUSD',
            venueAccount: 'BitMEX',
            securityId: '2',
          },
        ],
      })
    );
  }),
]

I've even tried with capturing all operation with graphql.operation and none was called. Whatever i try i get undefined from useQuery hook. I also have logged the handler at it prints it out as it exist
Screenshot 2023-01-24 at 18 47 40
There is any fetch mocking in the entire project. Another thing that maybe is worth to mention that we have axios installed - but this one is not taking part in the test (not imported in any place)

I've also investigated the query that is dispatched during this test:
Screenshot 2023-01-24 at 18 58 04

The thing is that there is nothing custom and different here than just "Get started" apollo setup + GraphQL mock setup 1:1 as per MSW docs says - at least it seems to, if i not did any major mistake here.

mockServiceWorker.js is shipped to production

"src/mockServiceWorker.js"

Hey there! In the generated mockServiceWorker.js file, it states to not ship/serve this file to production. By including this file in the assets: [] array, angular will package this file in its production build. Is there any way we could tell angular to serve this file for testing and development but do not include it in the production bundle?

Otherwise this is a very helpful example! Thank you for taking the time to create it :)

thrown: "API not configured" error

Might not be related directly to mswjs but switching from mocking fetch to msw introduced this. Running DEBUG=*, but unclear if the component is calling something that's not mocked:

  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression CallExpression: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee MemberExpression: enter +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee MemberExpression: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object CallExpression: enter +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object CallExpression: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0] CallExpression: enter +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0] CallExpression: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].callee MemberExpression: enter +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].callee MemberExpression: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].callee.object MemberExpression: enter +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].callee.object MemberExpression: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].callee.object MemberExpression: exit +1ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].callee MemberExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].arguments[0] TemplateLiteral: enter +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].arguments[0] TemplateLiteral: Recursing into... +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0].arguments[0] TemplateLiteral: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object.arguments[0] CallExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee.object CallExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression.callee MemberExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6].expression CallExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body.body[6] ExpressionStatement: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1].body BlockStatement: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression.arguments[1] ArrowFunctionExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1].expression CallExpression: exit +0ms
  babel program.body[8].expression.arguments[1].body.body[1] ExpressionStatement: exit +0ms
  babel program.body[8].expression.arguments[1].body BlockStatement: exit +0ms
  babel program.body[8].expression.arguments[1] ArrowFunctionExpression: exit +0ms
  babel program.body[8].expression CallExpression: exit +0ms
  babel program.body[8] ExpressionStatement: exit +0ms
  http override patching "http" module... +0ms
  http override patching "https" module... +1ms
  XHR patching "XMLHttpRequest" module... +0ms
  http override restoring modules... +86ms
  XHR restoring modules... +86ms
 FAIL  src/widgets/help/__tests__/HelpPanel.tests.tsx
  โ— HelpPanel and StaticHelpPanel โ€บ HelpPanel successfully renders articles & title given mocked data

    thrown: "API not configured"

      at _getError (node_modules/jest-circus/build/utils.js:566:18)
          at Array.map (<anonymous>)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)

The title of the component passes assertion but the data from the payload doesn't render. I would imagine it should hit these handlers:

export const handlers = [
    /* catch all */
    rest.get('*', (req, res, ctx) => {
        console.error(`Please add requst handler for ${req.url.toString()}`);
        return res(ctx.status(500), ctx.json({ error: 'Please add request handler' }));
    }),
    rest.post('*', (req, res, ctx) => {
        console.error(`Please add POST requst handler for ${req.url.toString()}`);
        return res(ctx.status(500), ctx.json({ error: 'Please add request handler' }));
    }),
];

I've mocked the server here:

        server.use(
            rest.post(appServerUrl('/api/v1/help/articles'), (req, res, { json }) => {
                return res(json(articleResponseJson));
            }),
        );

NetworkError at XMLHttpRequest.send

Test:

describe('When function authApi its passed', () => {
    test("Authentication services", async () => {
        const user: Response<UserInfo> = await request.get('user');
        // expect(userMock?.lastName).toEqual('Valencia');
        expect(user.payload?.lastName).toEqual('Valencia');

    });
})

The feature:

import ky from 'ky';

const api = ky.extend({
    prefixUrl: '/api/',
    retry: 0,
});
export const request: Request = {
    get: async <R>(url: string) => {
        const res: Response<R> = await api.get(url).json();
        return res;
    },
}

Server configuration
Screenshot 2022-05-19 at 17 27 17

The error

NetworkError
at XMLHttpRequest.send (/Users/project/ui/.yarn/cache/xhr2-npm-0.2.1/node_modules/xhr2/lib/xhr2.js:281:19)
at /Users/project/ui/.yarn/cache/whatwg-fetch-npm-3.6.2/node_modules/whatwg-fetch/dist/fetch.umd.js:600:11
at new Promise (<anonymous>)
at fetch (/Users/project/ui/.yarn/cache/whatwg-fetch-npm-3.6.2/node_modules/whatwg-fetch/dist/fetch.umd.js:507:12)
at /Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/utils/time.js:11:10
at new Promise (<anonymous>)
at timeout (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/utils/time.js:3:69)
at Ky._fetch (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/core/Ky.js:213:23)
at async fn (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/core/Ky.js:84:28)
at async Promise.result.<computed> [as json] (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/core/Ky.js:120:39)

Why am i importing XMLHttpRequest library:
ReferenceError: XMLHttpRequest is not defined

What could be the issue?

Add Storybook static build tests

Context

In our current Storybook integration example we feature in-browser tests against the running Storybook.

What

We need to add tests for the static Storybook build (as after running the yarn build-storybook command). We will take the static build, open it locally (via Puppeteer since we're already using it in the example), and test two scenarios:

Our current component only features the useFetch hooks that calls fetch underneath. We'd have to create another component that does a request via XMLHttpRequest, create a story for it, and cover it with tests.

Steps

  1. Create a new React component the same as the current GitHubUser component. In the new component, use XMLHttpRequest to make a request, remove the useFetch hook, and the logic around it.
  2. Create a new story for the newly created React component. Put it in the stories/[ComponentName].stories.js.
  3. Create a new E2E test in the e2e/[ComponentName].e2e.test.js. In this test use Puppeteer to load the locally build Storybook project, navigate to the story, and assert that it renders the elements based on the mocked data.

Question: Is it possible to intercept ALL requests?

MSW seems to require me to write down a very specific URL in order to capture my request in Jest. I just want to set up a server to capture every request regardless of the URL and then. turn the server off after my tests are finished.

I've tried the following:

  • .get('*'
  • .get(/.*/
  • .get(/**

None of these have worked.

Explicitally waiting for a network request

Hey there, I have been looking at the rest-react example and I notice that it does not explicitally wait for the network request to complete, which I think is typical in Cypress tests when using cy.server & cy.route

I assume this is not required because when the Cypress test runner arrives on this line:

cy.get('[data-testid="userId"').should(

it will wait for x seconds for that element to appear before failing. Because the msw handler defined here responds immediately, the React component will update, and Cypress will find the element.:

rest.post('/login', (req, res, ctx) => {

So I assume there is no need for us to explicitly wait in our tests for the network response?

I have forked this repo and added an assertion after the Login form is submitted, but it can never find the button.

https://github.com/jmcrthrs/examples

Perhaps you can clone the repo and run Cypress to see the behaviour, and if I am doing something wrong?

Karma example is unstable

Description of an issue

It is quite simple. Just clone the repo. Then run with-karma example. Run the tests a few times in a row. Observe that sometimes they fail.

After some investigation it was found that adding additional timeout, after starting the worker, solves the issue (looks like that at least).

this.beforeAll(async () => {
    await worker.start();
    // add timeout, 1s
    await new Promise((resolve) => window.setTimeout(resolve, 1000));
})

Environment

  • os: macOS

Add NextJS example

While very similar to CRA, the usage with NextJS has its deviations:

  • Next doesn't have an src directory (people don't know where to write the mocks)
  • Next doesn't have index.js (people don't know where to import the mocks)

This is confusing for newcomers. There must be a usage example.

Add example which uses Web Test Runner (@web/test-runner)

Is your feature request related to a problem? Please describe.

Karma was marked as deprecated on Apr 27, 2023 in karma-runner/karma#3846
Karma is widely used for real browser testing, and mswjs had provided an official example in https://github.com/mswjs/examples/tree/master/examples/with-karma

The maintainer team of karma has recommended Web Test Runner and jasmine-browser-runner as alternatives.
The former has backing from Chrome/BrowserStack/Netlify/SauceLabs, and has more npm downloads as well as GitHub stars.

Describe the solution you'd like

Add an example which shows how to use @web/test-runner with mswjs

Describe alternatives you've considered

N/A

Change intercepted payload in a single test at runtime

The issues filed here have been tremendously helpful so posting my ask here as it can help others as well. I'm trying to test for a deletion of a token from our UI dashboard. Posting a snippet but wanted to know if you can change your payload at runtime?

it('token should be deleted, () => {
      const tokenName = 'Toast';
      //...
      // define payloadBeforeDelete and payloadAfterDelete
      server.use(
            rest.get(tokenServerUrl('/tokens'), (req, res, { json }) => {
                return res(json(payloadBeforeDelete));
            }),
        );
        render(<MockAPITokenManagementWrapper />);
        await waitFor(() => expect(screen.getByTestId(`token-card-${tokenName}`)).toBeVisible());

        userEvent.click(screen.getByTestId(`token-card-${tokennGuid}-revoke-button`));
        userEvent.type(screen.getByTestId('revoke-token-dialog-token-input'), correct2FA);

        server.use(
            rest.get(tokenServerUrl('/tokens'), (req, res, { json }) => {
                return res(json(payloadAfterDelete));
            }),
        );
        userEvent.click(screen.getByRole('button', { name: /Revoke Access/i }));
        await waitFor(() => expect(screen.queryByText('Invalid code.')).not.toBeInTheDocument()); <-- this token exists
        await waitFor(() => expect(screen.queryByTestId(`token-card-${tokenName}`)).not.toBeInTheDocument());
})

token-card-Toast is still in the document so I'm unclear if you can actually call rest.get() twice in a single test.

Run tests in supported version of Node.js

Is your feature request related to a problem? Please describe.

The tests are currently run in Node.js 12.x

- image: cypress/browsers:node12.19.0-chrome86-ff82

The Node.js 12.x was EoL on 2022-04-30: https://github.com/nodejs/Release#end-of-life-releases

Describe the solution you'd like

Run tests on minimum supported version of Node.js, which is 16.x as of May'22.

Describe alternatives you've considered

N/A

Testing the correct data is passed to fetch

Perhaps this is the incorrect place, but I was wondering if unit testing that the correct data is passed to the endpoint is in scope when using msw.

I will use the example given here:

I would like to ensure that the arguments passed to fetch are correct. e.g. the first argument is '/login', the method is 'POST' etc.

I think this is a good idea to prevent regressions, however perhaps it is out of scope for the integration test linked above.

I am interested if anyone has an idea of how I would write my unit test when using msw.

In mswjs/examples/rest-angular worker.start() is not awaited

Hello! First off: thank you for your amazing work! I really like the idea behind MSW and I am trying to get it to work in in Angular, but it isn't as straight-forward (or perhaps I am just dumb).

In Vue, I could ensure, that I await the service worker to start before proceeding.

async function startWorkers(): Promise<void> {
  if (process.env.NODE_ENV) {
    await repositoryWorker.start();
  }
}

startWorkers().then(() => {
  const app = createApp(App).use(router).use(store).use(vuetify).mount("#app");
});

In Angular (13), I cannot easily switch to using top-level awaits and I do not know whether I should. I currently ended up using setTimeout, which I'd rather not, but I do not know how else to accomplish this.

In https://github.com/mswjs/examples/tree/master/examples/rest-angular I'd love to have the worker.start() being awaited, because I currently did everything in the tutorial by @timdeschryver , but my requests did not go through.
Knowing the possible reason (I spent a few hours looking into it when I tried Vue a few weeks ago), I thought it might be, that the request is fired before the mock service worker has actually started (request is fired in onInit of a component).

The following helped, but I wonder if there is a prettier way without having to use setTimeout):

(main.ts)

if (environment.production) {
  enableProdMode();
} else {
  worker.start()
}

setTimeout(() => platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err)), 100);

I'd also much more prefer to use the actual environment(.*).ts files for starting the worker, too.

Do you guys happen to have an idea of how to make this better? I just want to make sure the mock service worker is started before the first "request" is issued (or before the application even starts - whichever is easier) and if the mock service worker cannot be started for whatever reason, I wouldn't mind if the whole application doesn't start (in development mode obviously; production mode and its code shouldn't even know, that MSW exists).

Running examples fails with missing module 'msw'

Description

Running examples locally fails because 'msw' module isn't installed.

Steps to reproduce

git clone https://github.com/mswjs/examples
cd examples
yarn
cd examples/rest-react
yarn start

Expected behaviour

Example starts in browser

Screenshots

image

Jest tests all return ' No element indexed' error

I am running jest test suites for a Next.js app that uses Redux Toolkit. I'm using msw to mock any necessary calls to another api outside of the Next app that are handled by Redux Toolkit.

I have not mocked ALL of the RTK query endpoints, only the ones which I am currently using in my tests.


The tests run fine when I'm running without coverage generation via npm run test.

However, when I run with coverage reports via npm run test -- --coverage, all tests fail and they all have the same error:

- Test suite failed to run

    No element indexed by 9
    
     at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
      at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
      at mapSourcePosition (node_modules/source-map-support/source-map-support.js:214:42)
      at wrapCallSite (node_modules/source-map-support/source-map-support.js:358:20)
      at node_modules/source-map-support/source-map-support.js:399:26
          at Array.map (<anonymous>)
      at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:398:30)

I found that if I set the msw handlers to an empty array, the error doesn't appear. The few tests which require the API fail, as expected. However, the tests all run fine otherwise.

I'm unsure where to go from here. Any advice is greatly appreciated.

Asserting request payload (waitForRequest) in v2 documentation

After upgrading to v2, the code copied from the documentation is not functioning properly.

function waitForRequest(method: string, url: string) {
  let requestId = ''

  return new Promise<MockedRequest>((resolve, reject) => {
    server.events.on('request:start', (req) => {
      const matchesMethod = req.method.toLowerCase() === method.toLowerCase()
      const matchesUrl = matchRequestUrl(req.url, url).matches

      if (matchesMethod && matchesUrl) {
        requestId = req.id
      }
    })

    server.events.on('request:match', (req) => {
      if (req.id === requestId) {
        resolve(req)
      }
    })

    server.events.on('request:unhandled', (req) => {
      if (req.id === requestId) {
        reject(
          new Error(`The ${req.method} ${req.url.href} request was unhandled.`),
        )
      }
    })
  })
}

Is it still possible to retrieve a request reference and write request assertions (i.e., determine if the correct request payload was sent) in v2? I am unable to find this information in the new documentation.

Just tried running this on my Mac M1 under Rosetta 2 - fails

I am literally just trying to start up the application

Screenshot 2021-03-18 at 17 46 50

Screenshot 2021-03-18 at 17 46 55

Some system info

arch: 'x64',
  platform: 'darwin',
  release: {
    name: 'node',
    lts: 'Fermium',
    sourceUrl: 'https://nodejs.org/download/release/v14.16.0/node-v14.16.0.tar.gz',
    headersUrl: 'https://nodejs.org/download/release/v14.16.0/node-v14.16.0-headers.tar.gz'
  },

Use custom "fetch" when creating "ApolloClient"

Otherwise requests on initial component render are not intercepted: the call to window.fetch is statically referenced and doesn't execute the custom deferred logic of MSW.

export const client = new ApolloClient({
  uri: '/graphql',
  fetch: (...args) => window.fetch(...args),
});

mockup msw doesn't work

Sorry for my bad english but this answer doesn't work
my preview.js is this

const mockedQueryClient = new QueryClient();

addDecorator((Story) => (
  <QueryClientProvider client={mockedQueryClient}>
    <ThemeProvider theme={daviLabsTheme}>
      <ReactQueryDevtools />
      <Story />
    </ThemeProvider>
  </QueryClientProvider>
))

if (typeof global.process === 'undefined') {
  const { worker } = require("../mocks/server");
  worker.start();
}

but the console in firefox and chrome said

index.js:511 Uncaught (in promise) Error: [MSW] Failed to register a Service Worker for scope ('http://localhost:6006/') with script ('http://localhost:6006/mockServiceWorker.js'): Service Worker script does not exist at the given path.

Did you forget to run "npx msw init <PUBLIC_DIR>"?

Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init
    at getWorkerInstance (index.js:511:1)
    at async startWorkerInstance (index.js:1645:1)


I tried with Mock Service Worker and execute npx msw init public/ but doesnt work , the react query is work when the api is ON, but I need to creaate and put the mock

Please help me to create correct mock

my handler.ts : I tried to create mock in two ways but doesnt wotk this same handler I put in storybook but doens't work

import { graphql, rest } from 'msw'
/**
 * a list of handlers (endpoints) to emulate (mock) a actual implementation
 */
export const handlers = [
    graphql.query('listBanksAch', (req, res, ctx) => {
        return res(
            ctx.data({
                tpAccounts: [
                    {
                        "id": 1,
                        "name": "Cuenta de ahorros"
                    },
                    {
                        "id": 2,
                        "name": "Cuenta Corriente"
                    },
                ]
            }),
        )
    }),
    rest.post("http://localhost:4005/graphql", (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json([
                {
                    "id": 1,
                    "name": "Cuenta de ahorros"
                },
                {
                    "id": 2,
                    "name": "Cuenta Corriente"
                },
            ])
        );
    })
]

My component is :

interface Props {
    /**
    * Open / close dialog
    */
    open: boolean;
    /**
     * Close dialog
     */
    onClose: () => void;
    /**
    * Function get form values
    */
    handleSubmit: (data: any) => void;
    /**
     * Init data to form
     */
    initData?: IFormACH;
}

export const DialogFormACH: FC<Props> = ({
    onClose,
    handleSubmit,
    open,
    initData,
}) => {


    const { banksACHData , typesAccountsACH} = useGetDataACH(open)


    const onSubmit = (data: any) => {
        handleSubmit(data);
        onClose();
    }
    return (
        <LayoutDialog
            open={open}
            onClose={onClose}
            fullWidth
            title={'ACH'}
            isLoading={banksACHData.isLoading || typesAccountsACH.isLoading}
        >
            <FormACH
                onSubmit={onSubmit}
                optionsBank={banksACHData.data!}
                optionsTypeCount={typesAccountsACH.data!}
                initData={initData}
            />
        </LayoutDialog>
    )
}

the hook is next:

const getTypesBankACH = async (): Promise<ListBanksAch[]> => {
    const query =
        `query  {
        listBanksAch {
            name
            nit
        }
    }`
    const { data: { data } } = await msListApi().post<IResponseBankACH>('/graphql', { query })

    return data.listBanksAch;
};

const geTypesAccounts = async (): Promise<TpAccount[]> => {
    const query =
        `query  {
        tpAccounts {
            id
            name
        }
    }`
    const { data: { data } } = await msListApi().post<ITypesAccountResponse>('/graphql', { query })

    return data.tpAccounts;
};

export const useGetDataACH = (open:boolean) => {
    const banksACHData = useQuery(['listBankACH',open],
        () => getTypesBankACH(),
        {
            enabled: open
        }
    )

    const typesAccountsACH = useQuery(['listAccountsACH',open],
        () => geTypesAccounts(),
        {
            enabled: open
        }
    )

    return {
        banksACHData,
        typesAccountsACH,
    }

and storybook is

export default {
    title: 'Molecules/Dialog/DialogFormACH',
    component: DialogFormACH,
    args: {
        handleSubmit: action('handleSubmit')
    },
    parameters: {
        layout: 'centered',

    },
} as ComponentMeta<typeof DialogFormACH>;

const Template: ComponentStory<typeof DialogFormACH> = (args) => {
    const [isOpen, setIsOpen] = useState(false);
    return (
        <>
            <Button onClick={() => setIsOpen(true)} variant='contained'>Open Dialog</Button>
            <DialogFormACH {...args} open={isOpen} onClose={() => setIsOpen(false)} />
        </>
    )
}


export const DialogFormACHExample = Template.bind({});
DialogFormACHExample.args = {};

Why mockServiceWorker not read in the browser and how put mock in storybook? , thanks

GraphQL Default Response Override Test Example

I'd like to see an example test that resets the handlers between tests and configures a unique response per test.

My understanding is that I should be able to add an "override" handler in individual tests that tweak a default configuration.

Here is some pseudo-code that represents what I think is needed for setup / use.

setupTests.js

import { handlers } from './mocks'
const server = setupServer(...handlers)
beforeAll(() => {
  server.listen()
})
afterEach(() => {
  server.resetHandlers()
})
afterAll(() => {
  server.close()
})

Test:

// Appropriate imports here to get access to server
it('Uses default setup', () => {
  // Test here
}

it('Uses custom setup', () => {
  server.use(
    graphql.query('SameQueryAsSetup`, (req, res, ctx) => {
      // Return different response from default
    });
  // Rest of test
}

MSW do not intercept GraphQL requests at all

I've tried every possible solution described on the internet, but nothing seems to help.

I created a mock server and am trying to intercept a GraphQL call:

./setup/setup-server.ts

const handlers = [
graphql.query<GetOperation, GetOperationVariables>(
    'GetOperation'
    (req, res, ctx) => {
      // Nothing showing in console
      console.log(req.variables);
      return res(
        ctx.data({
          operation: [] // mocked operation
        })
      );
    }
  ),
]

./graphql/use-get-operation.ts

export const GET_OPERATION_BY_ID_DEFAULT = gql`
  query GetOperation($idOrContractNumber: String!) {
    operation(input: { idOrContractNumber: $idOrContractNumber }) {
      id
      modality
      totaltaxes
      exchangeRate
    }
  }
`;

The call is not intercepted.

I've already tried:

  • Import jest-fetch-mock in the configuration file;
  • Start the server in setupFiles.js (as exemplified in the documentation);
  • Start the server in the file directly in the test;
  • Use regex instead of string in the operation name;

Nothing seems to work.

I tried to create both queries and mutations and it didn't work.

MSW version used: 0.33.0

โ˜๏ธ Question: Can I Spy on the server in my jest tests?

Posted the question on SO and also dropping it here.

I'm starting to use the msw (mock service worker) after watching this example of how to use it for testing API calls in React applications.

Is there any way that we can spy on the mock service worker?

For example:

import React from 'react'
import { render, fireEvent, act, await } from '@testing-library/react'
import { rest } from 'msw'
import { setupServer } from 'msw/node'

import SearchBox from '.'

const fakeServer = setupServer(
  rest.get(
    'https://api.flickr.com/services/rest/?method=flickr.photos.search',
    (req, res, ctx) => res(ctx.status(200), ctx.json({ data: { photos: { photo: [] },},}))
  )
)

beforeAll(() => {fakeServer.listen()})
afterEach(() => {fakeServer.resetHandlers()})
afterAll(() => fakeServer.close())

test('it calls Flickr REST request when submitting search term', async () => {
  axios.get.mockImplementation(() => Promise.resolve({ data: {} }))
  const { getByLabelText } = render(<SearchBox />)
  const input = getByLabelText('Search Flickr')
  const submitButton = getByLabelText('Submit search')

  await act(async () => {
    await fireEvent.change(input, { target: { value: 'Finding Wally' } })
    await fireEvent.click(submitButton)
  })

  await wait()

  // TODO: assert that the fakeServer was called once and with the correct URL
})

The component to test looks like this:

import React, { useState } from 'react'
import axios from 'axios'

import './index.css'

function SearchBox({ setPhotos }) {
  const [searchTerm, setSearchTerm] = useState('')

  const handleTyping = (event) => {
    event.preventDefault()
    setSearchTerm(event.currentTarget.value)
  }

  const handleSubmit = async (event) => {
    event.preventDefault()
    try {
      const restURL = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${
        process.env.REACT_APP_API_KEY
      }&per_page=10&format=json&nojsoncallback=1'&text=${encodeURIComponent(
        searchTerm
      )}`
      const { data } = await axios.get(restURL)
      const fetchedPhotos = data.photos.photo
      setPhotos(fetchedPhotos)
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <section style={styles.container}>
      <form action="" method="" style={styles.form}>
        <input
          aria-label="Search Flickr"
          style={styles.input}
          value={searchTerm}
          onChange={handleTyping}
        />
        <button
          aria-label="Submit search"
          style={styles.button}
          onClick={handleSubmit}
        >
          SEARCH
        </button>
      </form>
    </section>
  )
}

I have got a working test, but I feel it leans towards an implementation test since it uses a spy on the setPhotos

test('it calls Flickr REST request when submitting search term', async () => {
  const fakeSetPhotos = jest.fn(() => {})
  const { getByLabelText } = render(<SearchBox setPhotos={fakeSetPhotos} />)
  const input = getByLabelText('Search Flickr')
  const submitButton = getByLabelText('Submit search')

  await act(async () => {
    await userEvent.type(input, 'Finding Walley')
    await userEvent.click(submitButton)
  })

  await wait()

  expect(fakeSetPhotos).toHaveBeenCalledWith([1, 2, 3])
})

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.