Skip to content

Commit

Permalink
avoid side-effect with MSW server in vulcan utils
Browse files Browse the repository at this point in the history
  • Loading branch information
eric-burel committed Nov 26, 2021
1 parent 4d757aa commit 656339a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
8 changes: 4 additions & 4 deletions jest/setupFilesAfterEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
// @see https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom";

import { mswServer } from "@vulcanjs/utils";
import { getMswServer } from "@vulcanjs/utils";
// MSW setup
// TODO: storybook test might already initialize a worker (in preview.js),
// not sure yet of the interaction between this worker and the server we create here
// However, we still need a setup specific to Jest for non-storybook tests
// Enable API mocking before tests.
beforeAll(() => mswServer.listen());
beforeAll(() => getMswServer().listen());
// Reset any runtime request handlers we may add during the tests.
afterEach(() => mswServer.resetHandlers());
afterEach(() => getMswServer().resetHandlers());
// Disable API mocking after the tests are done.
afterAll(() => mswServer.close());
afterAll(() => getMswServer().close());
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ import {
} from "@vulcanjs/graphql";
import { OneFieldGraphql, OneFieldType } from "./fixtures/graphqlModels";

import { mswServer } from "@vulcanjs/utils";
import { getMswServer } from "@vulcanjs/utils";

beforeEach(() => {
// add relevant mocks
mswServer.use(...graphqlMutationStubsToMsw([createMock]));
getMswServer().use(...graphqlMutationStubsToMsw([createMock]));
});
const createMock: GraphqlMutationStub<any> = {
operationName: createOperationName(OneFieldGraphql),
Expand Down
16 changes: 15 additions & 1 deletion packages/utils/mswServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,18 @@
* @see https://mswjs.io/docs/api/setup-server/use
*/
import { setupServer } from "msw/node";
export const mswServer = setupServer();

let mswServer;
/**
* Return a global instance of MSW server
* (initialize the server during first call)
*
* NOTE: keep this code within a function to avoid side effectr when loading the package
* @returns
*/
export const getMswServer = () => {
if (!mswServer) {
mswServer = setupServer();
}
return mswServer;
};

0 comments on commit 656339a

Please sign in to comment.