mswjs / examples Goto Github PK
View Code? Open in Web Editor NEWExamples of Mock Service Worker usage with various frameworks and libraries.
Examples of Mock Service Worker usage with various frameworks and libraries.
In our current Storybook integration example we feature in-browser tests against the running Storybook.
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.
XMLHttpRequest
to make a request, remove the useFetch
hook, and the logic around it.stories/[ComponentName].stories.js
.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.One should not use /login
but an absolute url as states ref doc.
One of the users has reported that msw
package is included in the production bundle of the rest-react
example.
msw
must not be included in the production bundle.
Link for graphQL from here: https://mswjs.io/examples/ leads to a 404 (https://github.com/mswjs/examples/tree/main/examples/graphql-react-apollo)
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.
I tried example/example/rest-react ,while I opened http://localhost:3001 ,input sth, click submit button. Nothing happened .
expect: as http://10.0.0.6:3001. While click submit button,
John Maverick
f79e82e8-c34a-4dc7-a49e-9fadc0979fda
is shown.
Folks often struggle with getting relative URLs to work in JSDOM. Would be nice to add a new test to the existing jest-jsdom
example that feature the usage of relative request URLs.
MSW must not be included in the production bundle.
I use the environment file to add a module in development who load my MSW config.
You have an example here
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.
Running MSW 2.0 on Jest when JSDOM is not used allows us to skip patching undici. For that reason, we should show separate examples of setting up MSW on Jest with and without JSDOM
The tests are currently run in Node.js 12.x
Line 5 in 71a76d2
The Node.js 12.x was EoL on 2022-04-30: https://github.com/nodejs/Release#end-of-life-releases
Run tests on minimum supported version of Node.js, which is 16.x as of May'22.
N/A
docs says -> src/main.ts conditionally enables mocking in development environment.
But where is it there?
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:
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.:
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?
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),
});
While very similar to CRA, the usage with NextJS has its deviations:
src
directory (people don't know where to write the mocks)index.js
(people don't know where to import the mocks)This is confusing for newcomers. There must be a usage example.
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.
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
}
I am using Vite but not Create-React-App. I am totally newbie so I change the example graph-react-apollo
to graph-react-vite-apollo
.
Can I give you a PR?
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.
Hi there!
Following this article
There are minor changes that could be fixed on these examples:
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.
Add an example which shows how to use @web/test-runner
with mswjs
N/A
^0.20.0
expected and 0.20.1
actual, which is a valid SemVer match.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])
})
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.
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));
})
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?
There's a great Storybook usage setup from @yannbf that illustrates how to embed Mock Service Worker into Storybook. Consider creating a similar example in this repo.
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 :)
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;
},
}
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?
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).
I am literally just trying to start up the application
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'
},
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
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.
In the Remix + MSW example there is only one example with handlers that return 200.
But how should MSW be used with handlers that return 400, 500?
It's not clear how to use resetHandlers() or dynamic mock scenarios within a Remix app.
Trying to import ant reset handlers in a test doesn't work, because the server instance is only working within a entry.server.tsx file.
We use Lerna to manage nested packages and form a monorepo.
Let's use Yarn workspaces directly for managing the monorepo.
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));
}),
);
is there a specific reason why storybook doesn't use the msw addon (https://storybook.js.org/addons/msw-storybook-addon)?
would be lovely to have an example for how to use it
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
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:
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.
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:
Nothing seems to work.
I tried to create both queries and mutations and it didn't work.
MSW version used: 0.33.0
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.