Skip to content

End-to-End Tests With Playwright: Frontend, Backend and Database · Part 3 of 14 in the series

Part 3: One Config, Four Projects

Split the suite into four Playwright projects, one for each layer of the app: database, backend, frontend and end to end. Each gets a first small test that shows what kind of test lives there.

Quest objectives

  • Understand why a suite in sections tells you more than a pile of browser tests
  • Know what a Playwright project is, and use projects for layers instead of browsers
  • Write a test without a browser that reads the database through the app's own code
  • Send HTTP requests from a test with the request fixture
  • Answer the page's requests from the test with page.route
  • Run one section alone, and list the tests of all of them

The suite from part 2 knows one kind of test: a browser against the running app. Carry on like that and every question is asked through the page, including the ones the page has little to do with. Does the database refuse a negative reward? Does the API answer an unknown id with 404?

This part gives the suite its shape instead: four sections, one for each layer, set up as four Playwright projects in one config. Each section gets one small test for now, to show its kind. The weak spot from the end of part 2 stays for one more part.

One signpost, four ways: to the browser, to the server, to the database, and one path that leads through all of them.
One signpost, four ways: to the browser, to the server, to the database, and one path that leads through all of them.

Why sections?

There are three reasons to sort tests by the layer they check:

  • A failure tells you where to look. If only the database tests are red, you know where to start. If only the end-to-end tests are red, every layer works alone and the fault is in how they fit together.

  • Details are tested where they are cheap. Twenty kinds of invalid input are twenty short HTTP requests for the backend tests. Through the form in a browser the same checks take longer, and each of them can fail for reasons that have nothing to do with the input.

  • The slow tests stay few. The end-to-end tests only have to show that the layers work together, not every rule of every layer.

Playwright has the right tool for this. A project is a named group of tests with its own settings. In part 2 you had one, called chromium, and that is what projects are usually used for: the same tests in several browsers. Nothing says a project has to be a browser, though. Here each project is a layer, with its own folder and its own settings.

Four projects

First the folders, one for each section. The test file from part 2 moves into e2e, because a browser, the real API and the real database is what it has used all along:

questboard
$ mkdir tests/database tests/backend tests/frontend tests/e2e$ mv tests/quest-board.spec.ts tests/e2e/

Then the config. Replace the contents of playwright.config.ts:

playwright.config.ts
import { existsSync } from 'node:fs';
import { defineConfig, devices } from '@playwright/test';

// The tests read the same settings as the app. Where there is no .env, such as in a
// pipeline, the variables are set from outside.
if (existsSync('.env')) process.loadEnvFile();

const api = 'http://localhost:3000';
const web = 'http://localhost:5173';

export default defineConfig({
  reporter: [['list'], ['html']],
  use: {
    trace: 'on-first-retry',
  },
  projects: [
    {
      name: 'database',
      testDir: './tests/database',
    },
    {
      name: 'backend',
      testDir: './tests/backend',
      use: { baseURL: api },
    },
    {
      name: 'frontend',
      testDir: './tests/frontend',
      use: { ...devices['Desktop Chrome'], baseURL: web },
    },
    {
      name: 'e2e',
      testDir: './tests/e2e',
      use: { ...devices['Desktop Chrome'], baseURL: web },
    },
  ],
  // Playwright starts both servers before the tests and stops them afterwards.
  webServer: [
    {
      command: 'npm run dev:api',
      url: `${api}/api/health`,
      reuseExistingServer: !process.env.CI,
    },
    {
      command: 'npm run dev:web',
      url: web,
      reuseExistingServer: !process.env.CI,
    },
  ],
});

The first lines. process.loadEnvFile() is built into Node and reads the .env file into process.env. Playwright does not read .env itself. So far nobody missed it: the API gets its settings through --env-file in its npm script. The database tests will open their own connection, though, and for that the tests themselves need DATABASE_URL. The existsSync('.env') in front is there because loadEnvFile fails when there is no file, and in a pipeline there is none: the variables are set from outside there.

Two addresses. api and web are needed in several places now, so they get names.

The projects. Each has a name and a testDir, its own folder of tests. The testDir for the whole config is gone. What sets the four apart is their use:

  • database has none. Its tests need no browser and no address.

  • backend gets the address of the API as baseURL. Its tests send HTTP requests there. It has no browser either.

  • frontend and e2e get a browser, devices['Desktop Chrome'], and the address of the page.

Playwright starts a browser only for a test that asks for a page. The tests of database and backend never do, so they run without one.

webServer is as it was, only with the two names in place of the addresses.

One test for each section

The e2e folder has its file already. The other three get one small test each. Start at the bottom, with tests/database/connection.spec.ts:

tests/database/connection.spec.ts
import { expect, test } from '@playwright/test';
import { connect } from '../../server/db/client.ts';
import { quests } from '../../server/db/schema.ts';

test('the quests table can be read', async () => {
  const { db, pool } = connect(process.env.DATABASE_URL!);

  const rows = await db.select().from(quests);

  expect(Array.isArray(rows)).toBe(true);
  await pool.end();
});

Look at the function: async () =>. It asks for no page and for no other fixture. A Playwright test does not need a browser. It is a function that the test runner calls, and whether a browser plays a part is up to the test.

This one imports connect and the quests table from the app, the same code the API works with. It connects to the database in DATABASE_URL, reads the table and closes its pool again. The expect has no await here: it looks at a plain value, not at a page, so there is nothing to wait for.

The test cannot claim more than "reading works and gives a list". It reads your development database and cannot know what is in it. Real database tests come in part 5.

One layer up, tests/backend/health.spec.ts:

tests/backend/health.spec.ts
import { expect, test } from '@playwright/test';

test('the API reports that it is healthy', async ({ request }) => {
  const response = await request.get('/api/health');

  expect(response.status()).toBe(200);
  expect(await response.json()).toEqual({ ok: true });
});

This test asks for the request fixture. It is an HTTP client: it sends requests straight from the test, without a browser. The path /api/health is completed with the baseURL of the project, the address of the API. The answer has a status and a body, and the test checks both.

The third one runs in the browser, tests/frontend/board.spec.ts:

tests/frontend/board.spec.ts
import { expect, test } from '@playwright/test';

test('lists the quests the API sends', async ({ page }) => {
  // The page never reaches the real API: this answer comes from the test.
  await page.route('**/api/quests', (route) =>
    route.fulfill({
      json: [
        { id: 1, title: 'Find the lost sword', reward: 50, done: false, createdAt: '2026-01-01T10:00:00Z' },
        { id: 2, title: 'Feed the dragon', reward: 10, done: true, createdAt: '2026-01-01T11:00:00Z' },
      ],
    }),
  );

  await page.goto('/');

  await expect(page.getByRole('listitem')).toHaveText([/Find the lost sword/, /Feed the dragon/]);
  await expect(page.getByText('1 of 2 quests open')).toBeVisible();
});

page.route is the idea of this whole section. Before the page is opened, the test tells the browser: when a request goes to an address that matches **/api/quests, do not send it, call this function instead. route.fulfill then answers the request, here with two quests as JSON. The page gets its list from the test. The real API is never asked, and what is in your development database does not matter.

That makes the test exact. It knows what the list holds, so it can say what the page has to show. toHaveText with a list checks that the locator finds as many elements as the list has entries, with these texts, in this order. The entries are regular expressions, because a list item contains more than the title: the reward is in it too. The last line checks the count under the list.

The fourth section, e2e, has the two tests from part 2. They moved, and nothing in them changed.

Run the sections

Run everything:

questboard
$ npx playwright testRunning 5 tests using 4 workers  ✓  2 [backend] › tests/backend/health.spec.ts:3:1 › the API reports that it is healthy (28ms)  ✓  3 [e2e] › tests/e2e/quest-board.spec.ts:3:1 › shows the board (129ms)  ✓  1 [frontend] › tests/frontend/board.spec.ts:3:1 › lists the quests the API sends (148ms)  ✓  5 [database] › tests/database/connection.spec.ts:5:1 › the quests table can be read (14ms)  ✓  4 [e2e] › tests/e2e/quest-board.spec.ts:9:1 › adds a quest (164ms)  5 passed (2.3s)

Five tests, and the project of each is in brackets. New is "using 4 workers". A worker is a process that runs tests. Playwright starts several of them and hands each a test file, so files run at the same time: four files, four workers. How many workers there are depends on your machine, and with several at work your lines may come in a different order.

To run one section alone, you name its project. Add a script for each to package.json:

package.json
"scripts": {
  "dev:api": "node --env-file=.env --watch server/index.ts",
  "dev:web": "vite",
  "build": "vite build",
  "start": "node --env-file=.env server/index.ts",
  "db:generate": "drizzle-kit generate",
  "db:migrate": "node --env-file=.env server/db/migrate.ts",
  "typecheck": "vue-tsc --noEmit",
  "test": "playwright test",
  "test:database": "playwright test --project=database",
  "test:backend": "playwright test --project=backend",
  "test:frontend": "playwright test --project=frontend",
  "test:e2e": "playwright test --project=e2e"
},

--project limits a run to the project with that name:

questboard
$ npm run test:backend> questboard@1.0.0 test:backend> playwright test --project=backendRunning 1 test using 1 worker  ✓  1 [backend] › tests/backend/health.spec.ts:3:1 › the API reports that it is healthy (19ms)  1 passed (1.6s)

The two lines with > are npm saying what it runs. When you want to know which tests there are, and in which section, without running them, ask for the list:

questboard
$ npx playwright test --listListing tests:  [database] › tests/database/connection.spec.ts:5:1 › the quests table can be read  [backend] › tests/backend/health.spec.ts:3:1 › the API reports that it is healthy  [frontend] › tests/frontend/board.spec.ts:3:1 › lists the quests the API sends  [e2e] › tests/e2e/quest-board.spec.ts:3:1 › shows the board  [e2e] › tests/e2e/quest-board.spec.ts:9:1 › adds a questTotal: 5 tests in 4 files

That is a quick way to make sure a new test file landed in the section you meant.

What you have now

A suite with four sections in one config, a first test in each that shows what kind of test belongs there, and commands that run all of them or one alone.

What you do not have yet is tests you can trust. database, backend and e2e still work on your development database, and every test that needs the API shares the one server. The test "adds a quest" is still green for the wrong reason. In the next part that changes: every worker gets a database of its own.

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.