valendres / playwright-msw

A Mock Service Worker API for Playwright
MIT License
162 stars 22 forks source link

Why is MSW `http` added to test fixtures in doc examples? #100

Open iulspop opened 2 months ago

iulspop commented 2 months ago

Is MSW http added simply for convenience of not having to re-import from MSW in tests files?

Here's an example from the docs:

import { test as base, expect } from '@playwright/test';
import { http } from 'msw';
import type { MockServiceWorker } from 'playwright-msw';
import { createWorkerFixture } from 'playwright-msw';

import handlers from './handlers';

const test = base.extend<{
  worker: MockServiceWorker;
  http: typeof http;
}>({
  worker: createWorkerFixture(handlers),
  http
});

export { expect, test };
  test.only('should allow mocks to be overridden on a per test basis', async ({
    page,
    worker,
    http
  }) => {
    await worker.use(
      http.get('/api/users', async () => {
        await delay(250);
        return new HttpResponse(null, {
          status: 403,
        });
      }),
    );
    ...

I decided to go more with an API like this so I don't add http to the test fixtures, instead I import a handler with defaults I overwrite for specific tests:

import { faker } from '@faker-js/faker'
import { getUser } from './handlers'
import { expect, test } from './test'

test.describe('developer dashboard page', () => {
  test('given user is not logged in', async ({ page, worker, loginPage, devDashboardPage }) => {
    await test.step('then navigate to dashboard', async () => {
      await devDashboardPage.goto()
      await expect(page, 'should redirect to /login').toHaveURL(/login/)
    })

    await test.step('then sign in', async () => {
      const login = faker.internet.userName()
      await worker.use(getUser({ login }))
      await loginPage.signInLink().click()
      await expect.soft(page, 'should redirect to /').toHaveURL(/\//)
      await expect(devDashboardPage.userProfileLogin(login), 'should load user info').toBeVisible()
    })

    await test.step('then sign out', async () => {
      await devDashboardPage.userProfileImage().click()
      await devDashboardPage.signOutButton().click()
      await expect(page, 'should redirect to /login').toHaveURL(/login/)
    })
  })
})