msw/node#setupServer TypeScript Examples

The following examples show how to use msw/node#setupServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: tests-utils.mock-server.ts    From jitsu with MIT License 7 votes vote down vote up
/**
 * Mock server setup
 */

/**
 * Sets up the mock server with some default endpoints that are required globally
 * along with the endpoints provided by user. User endpoints will override the defaults
 * if their keys match.
 *
 * @param endpoints
 * Endpoints to use for the mock server.
 *
 * Use `setupMockServer.endpoints.catalog` to get some handy defaults.
 *
 * To override one of the required endpoints just copy it from
 * `setupMockServer.endpoints.required`, change the data or the implementation
 * and pass it in `endpoints` under the same key as it appears in the
 * `setupMockServer.endpoints.required` catalog.
 *
 * @returns configured mock server instance.
 */
export function setupMockServer(endpoints: MockServerConfig = {}): SetupServerApi {
  const _endpoints: MockServerConfig = {
    ...mockObligatoryEndpoints,
    ...mockEndpointsCatalog,
    ...endpoints,
  }
  const _endpointsList = Object.values(_endpoints).map(({ responseData, requestFactory }) =>
    requestFactory(responseData)
  )
  return setupServer(..._endpointsList)
}
Example #2
Source File: RollbarApi.test.ts    From backstage with Apache License 2.0 6 votes vote down vote up
describe('RollbarApi', () => {
  describe('getRequestHeaders', () => {
    it('should generate headers based on token passed in constructor', () => {
      expect(getRequestHeaders('testtoken')).toEqual({
        headers: {
          'X-Rollbar-Access-Token': `testtoken`,
        },
      });
    });
  });

  describe('getAllProjects', () => {
    const server = setupServer();
    setupRequestMockHandlers(server);

    const mockBaseUrl = 'https://api.rollbar.com/api/1';

    const mockProjects: RollbarProject[] = [
      { id: 123, name: 'abc', accountId: 1, status: 'enabled' },
      { id: 456, name: 'xyz', accountId: 1, status: 'enabled' },
    ];

    const setupHandlers = () => {
      server.use(
        rest.get(`${mockBaseUrl}/projects`, (_, res, ctx) => {
          return res(ctx.json({ result: mockProjects }));
        }),
      );
    };

    it('should return all projects with a name attribute', async () => {
      setupHandlers();
      const api = new RollbarApi('my-access-token', getVoidLogger());
      const projects = await api.getAllProjects();
      expect(projects).toEqual(mockProjects);
    });
  });
});
Example #3
Source File: slices.spec.tsx    From slice-machine with Apache License 2.0 6 votes vote down vote up
server = setupServer(
  rest.post("/api/slices/create", (_, res, ctx) => {
    return res(
      ctx.json({
        screenshots: {},
        warning: null,
        variationId: "default",
      })
    );
  })
)
Example #4
Source File: ProductionApi.test.ts    From backstage with Apache License 2.0 6 votes vote down vote up
describe('The production Airbrake API', () => {
  const productionApi = new ProductionAirbrakeApi(localDiscoveryApi);
  const worker = setupServer();
  setupRequestMockHandlers(worker);

  it('fetches groups using the provided project ID', async () => {
    worker.use(
      rest.get(
        'http://localhost:7007/api/airbrake/api/v4/projects/123456/groups',
        (_, res, ctx) => {
          return res(ctx.status(200), ctx.json(mockGroupsData));
        },
      ),
    );

    const groups = await productionApi.fetchGroups('123456');

    expect(groups).toStrictEqual(mockGroupsData);
  });

  it('throws if fetching groups was unsuccessful', async () => {
    worker.use(
      rest.get(
        'http://localhost:7007/api/airbrake/api/v4/projects/123456/groups',
        (_, res, ctx) => {
          return res(ctx.status(500));
        },
      ),
    );

    await expect(productionApi.fetchGroups('123456')).rejects.toThrow();
  });
});
Example #5
Source File: LoginModal.spec.tsx    From slice-machine with Apache License 2.0 6 votes vote down vote up
server = setupServer(
  rest.post("/api/auth/start", (_, res, ctx) => {
    return res(ctx.json({}));
  }),
  rest.post("/api/auth/status", (_, res, ctx) => {
    return res(
      ctx.json({
        status: "ok", //"error" | "ok" | "pending";
        userId: "foo",
      })
    );
  })
)
Example #6
Source File: AllureReportComponent.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('ExampleComponent', () => {
  const server = setupServer();
  // Enable sane handlers for network requests
  setupRequestMockHandlers(server);

  // setup mock response
  beforeEach(() => {
    server.use(
      rest.get('/*', (_, res, ctx) => res(ctx.status(200), ctx.json({}))),
    );
  });

  it('should render', async () => {
    const rendered = await renderInTestApp(
      <ThemeProvider theme={lightTheme}>
        <EntityProvider
          entity={{
            apiVersion: 'backstage.io/v1alpha1',
            kind: 'Component',
            metadata: { name: 'test' },
          }}
        >
          <AllureReportComponent />
        </EntityProvider>
      </ThemeProvider>,
    );
    expect(rendered.getByText('Missing Annotation')).toBeInTheDocument();
  });
});
Example #7
Source File: server.mock.ts    From office-booker with MIT License 6 votes vote down vote up
server = setupServer(
  mockGetConfig(createFakeConfig()),
  rest.get('*', (req, res, ctx) => {
    console.log(req.method, req.url.href);
    return res(ctx.status(404));
  }),
  rest.delete('*', (req, res, ctx) => {
    console.log(req.method, req.url.href);
    return res(ctx.status(404));
  }),
  rest.post('*', (req, res, ctx) => {
    console.log(req.method, req.url.href);
    return res(ctx.status(404));
  }),
  rest.put('*', (req, res, ctx) => {
    console.log(req.method, req.url.href);
    return res(ctx.status(404));
  })
)
Example #8
Source File: client.test.ts    From backstage with Apache License 2.0 6 votes vote down vote up
describe('Catalog GraphQL Module', () => {
  const worker = setupServer();
  setupRequestMockHandlers(worker);

  const baseUrl = 'http://localhost:1234';

  it('will return the entities', async () => {
    const expectedResponse = [{ id: 'something' }];

    worker.use(
      rest.get(`${baseUrl}/api/catalog/entities`, (_, res, ctx) =>
        res(ctx.status(200), ctx.json(expectedResponse)),
      ),
    );

    const client = new CatalogClient(baseUrl);

    const response = await client.list();

    expect(response).toEqual(expectedResponse);
  });

  it('throws an error with the text', async () => {
    const expectedResponse = 'something broke';

    worker.use(
      rest.get(`${baseUrl}/api/catalog/entities`, (_, res, ctx) =>
        res(ctx.status(500), ctx.text(expectedResponse)),
      ),
    );

    const client = new CatalogClient(baseUrl);

    await expect(() => client.list()).rejects.toThrow(expectedResponse);
  });
});
Example #9
Source File: testServer.ts    From raspiblitz-web with MIT License 6 votes vote down vote up
server = setupServer(
  rest.get("*", (req, res, ctx) => {
    console.error(`Add request handler for ${req.url.toString()}`);
    return res(
      ctx.status(500),
      ctx.json({ error: "Missing request handler." })
    );
  })
)
Example #10
Source File: FossaClient.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
server = setupServer()
Example #11
Source File: product.test.ts    From Fashionista with MIT License 5 votes vote down vote up
server = setupServer(
  rest.get(/\/catalog$/, (_, res, ctx) => {
    return res(ctx.json(mockedProducts));
  })
)
Example #12
Source File: GitLabDiscoveryProcessor.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
server = setupServer()
Example #13
Source File: server.ts    From frontend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
server = setupServer(...handlers)
Example #14
Source File: budget.api.mocked.it.ts    From budget-angular with GNU General Public License v3.0 5 votes vote down vote up
describe("BudgetApi mocked TCP/IP", () => {
  let api: BudgetApi;
  const server = setupServer(createGetBudgetsStub());

  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      providers: [
        BudgetApi,
        {
          provide: ConfigProvider,
          useValue: {
            getConfig: () => ({ apiUrl: "/api" }),
          },
        },
      ],
    });

    api = TestBed.inject(BudgetApi);
  });

  it("gets available budgets", (done) => {
    // when
    api.getBudgets(new Period(12, 2020)).subscribe((budgets) => {
      // then
      expect(budgets[0].id).toBeDefined();
      expect(budgets[0].accountId).toBeDefined();
      done();
    });
  });

  it("returns an empty array if no budgets", (done) => {
    // when
    api.getBudgets(new Period(0, 0)).subscribe((budgets) => {
      // then
      expect(budgets).toEqual([]);
      done();
    });
  });
});
Example #15
Source File: server.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
server = setupServer(...handlers)
Example #16
Source File: node.ts    From mitojs with MIT License 5 votes vote down vote up
mswServer = setupServer(...handlers)
Example #17
Source File: json-rpc-server.mock.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
export function getServer(rpcUrl: string, mocks: Mock[]): SetupServerApi {
  const handlers = mocks.map((mock) => makeHandler(rpcUrl, mock));
  return setupServer(...handlers);
}
Example #18
Source File: server.ts    From pancake-toolkit with GNU General Public License v3.0 5 votes vote down vote up
server = setupServer(...handlers)
Example #19
Source File: CreateCustomTypeModal.spec.tsx    From slice-machine with Apache License 2.0 5 votes vote down vote up
server = setupServer(
  rest.post("/api/custom-types/save", (_, res, ctx) => {
    return res(ctx.json({}));
  })
)
Example #20
Source File: LoginComponent.test.tsx    From next-password-protect with MIT License 5 votes vote down vote up
server = setupServer()
Example #21
Source File: CatalogClient.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
server = setupServer()