PrepStack › Frontend › Frontend Testing & Tooling
Frontend Testing & Tooling interview cheat sheet
Jest/Vitest, mocking, Testing Library, Playwright, bundlers, Vite, package managers, CI
Senior frontend interviews almost always include a block on how you test and how your build works. Interviewers want to hear a clear testing strategy (what to test at which level), solid mocking and async habits, the Testing Library mindset, and how you keep E2E tests from going flaky. On the tooling side they probe bundlers, the Vite dev server, tree shaking, lockfiles and CI. Read the 15-minute list first, then use Quiz mode and answer out loud. Test-framework snippets are shown without output; the runnable ones rebuild the core idea in plain Node.
15-minute revision
- Pyramid: many unit, fewer integration, few E2E. Trophy (Kent C. Dodds): static checks at the base, then unit, with integration as the biggest layer, and a few E2E on top.
toBeusesObject.is(same reference or primitive).toEqualcompares structure recursively and ignoresundefinedprops.toStrictEqualalso checksundefinedprops, sparse arrays and class types.- Hook order per test:
beforeAllonce → (beforeEach→ test →afterEach) for each test →afterAllonce. Keep tests independent; reset state inbeforeEach. jest.fn()records calls;jest.spyOn(obj, 'm')wraps a real method and can be restored;jest.mock('./mod')replaces a whole module and is hoisted above imports.mockClearwipes calls;mockResetalso removes the implementation;mockRestorealso puts back the original (spies only). Turn onrestoreMocksin config.- Fake timers (
jest.useFakeTimers()/vi.useFakeTimers()) let you test debounce, polling and timeouts instantly withadvanceTimersByTime. - Mock the network, not your code: MSW intercepts
fetch/XHR at the request level, so the same handlers work in Jest, Vitest, Storybook and the browser. - Always
await(orreturn) promises in tests. A forgottenawaitgives a false pass. Useawait expect(p).rejects.toThrow()for errors. - Testing Library: test what the user sees. Query priority:
getByRole>getByLabelText> placeholder > text > display value > alt/title >getByTestId. getBythrows if missing,queryByreturnsnull(assert absence),findByreturns a promise that retries (default 1000 ms). Preferuser-eventoverfireEvent.- Playwright auto-waits for actionability (visible, stable, enabled, receives events) and uses web-first assertions that retry. Never use fixed
waitForTimeoutsleeps. - Coverage shows what code ran, not what was verified. Branch coverage is the most useful metric; 100% lines can still miss bugs.
^1.2.3allows<2.0.0;~1.2.3allows<1.3.0;^0.2.3allows only<0.3.0. Commit the lockfile and usenpm ci/pnpm install --frozen-lockfilein CI.- Vite dev: serve source as native ESM on demand and pre-bundle dependencies once. Production: a real bundle (Rolldown since Vite 8, Rollup before).
- Tree shaking needs static ESM plus side-effect-free code (
"sideEffects": false). Code splitting comes from dynamicimport()and route-levellazy(). - Babel/SWC/esbuild only strip types. Only
tsc(ortsc --noEmitin CI) type-checks. ESLint finds bugs; Prettier formats; disable style rules that conflict with Prettier.
Testing foundations
Testing pyramid vs trophy, unit vs integration vs E2E
Balance tests by cost and confidence. For UI code, most confidence per minute comes from integration-style component tests.
- Unit test: one function, hook or small component in isolation. Fast and precise, but it can pass while the app is broken.
- Integration test: several units working together, for example a form component with its validation, state and a mocked API. In frontend this is usually rendering a feature with Testing Library.
- E2E test: a real browser against a running app (Playwright, Cypress). Highest confidence, but slowest and most likely to be flaky.
- The pyramid (Mike Cohn) says: lots of unit, fewer integration, fewest E2E, because cost and flakiness rise as you go up.
- The testing trophy (Kent C. Dodds) adds static analysis (TypeScript, ESLint) at the base and makes integration the widest layer: "Write tests. Not too many. Mostly integration."
- Pick the level by asking: what is the cheapest test that would catch this bug and still read like real usage?
Interview questions
- What is the difference between unit, integration and end-to-end tests?
- Testing pyramid or testing trophy: which do you follow for a React app?
- How do you decide what NOT to test?
Jest vs Vitest
Same describe/it/expect API. Vitest reuses your Vite config and handles ESM and TS natively; Jest is the long-standing standard with the biggest ecosystem.
- Jest (Meta, now under the OpenJS Foundation) transforms files with
babel-jestorts-jest/@swc/jest. Its native ESM support still needs an experimental Node flag. - Vitest runs on Vite's pipeline, so aliases, plugins and TS/JSX transforms are shared with your app. ESM and TypeScript work out of the box.
- APIs are almost the same:
jest.fn()↔vi.fn(),jest.mock()↔vi.mock(),jest.useFakeTimers()↔vi.useFakeTimers(). Migration is mostly search and replace. - Both run test files in parallel workers and default to a
nodeenvironment. Setjsdomorhappy-domfor DOM tests. - Vitest 4 made Browser Mode stable: tests can run in a real browser through a Playwright or WebdriverIO provider.
- Watch mode: Jest uses git to find changed files; Vitest uses Vite's module graph to rerun only tests that import the changed file.
Interview questions
- Why would you choose Vitest over Jest for a new project?
- What is the difference between jsdom and happy-dom?
- What does a test setup file usually contain?
Matchers, setup & teardown
Choose the right equality matcher and keep each test independent with beforeEach/afterEach.
toBe→Object.is. Use it for primitives and "same reference" checks.toEqual→ recursive value equality.toStrictEqual→ also checksundefinedproperties and class type.- Common matchers:
toBeTruthy,toBeNull,toBeDefined,toContain,toHaveLength,toMatch(/re/),toThrow,toBeCloseTo(floats),toMatchObject(subset). - Mock matchers:
toHaveBeenCalled,toHaveBeenCalledTimes(n),toHaveBeenCalledWith(...),toHaveBeenLastCalledWith(...). expect.any(Number),expect.objectContaining({...}),expect.arrayContaining([...])andexpect.stringContaining('..')loosen part of a match.beforeAll/afterAllrun once per file ordescribeblock;beforeEach/afterEachrun around every test. Hooks in an outerdescribealso wrap tests in inner blocks.test.each(orit.each) runs the same test over a table of inputs.test.onlyandtest.skipfocus or skip tests; never commit.only.
Interview questions
- Difference between
toBe,toEqualandtoStrictEqual? - When would you use
beforeAllinstead ofbeforeEach? - What makes a good unit test?
Testing async code
The runner only waits for what you return or await. A forgotten await means the assertion runs after the test already passed.
- Make the test
asyncandawaitthe code under test, orreturnthe promise. The runner waits for it to settle. - For errors:
await expect(promise).rejects.toThrow('msg')andawait expect(promise).resolves.toEqual(x). Forgettingawaithere also gives a false pass. expect.assertions(n)fails the test if exactlynassertions did not run. It is a safety net for code paths incatchor callbacks.- Old callback style: take a
doneargument and call it, ordone(err). Prefer promises; Vitest does not supportdoneand suggests wrapping the callback in a promise. - In the DOM, async UI changes need
await screen.findBy...orawait waitFor(() => ...), not immediategetBy. - Default test timeout is 5 seconds in both Jest and Vitest. A hanging test usually means a promise never settles or fake timers were not advanced.
Interview questions
- Why can an async test pass even though the assertion is wrong?
- How do you test that an async function throws?
- A test times out after 5 seconds. How do you debug it?
Mocking & snapshots
Mocks, spies & module mocks
fn creates a fake that records calls, spyOn wraps a real method, mock() swaps a whole module. Restore them after each test.
- Test double names: a stub returns canned data, a spy records calls on something real, a mock is a fake with expectations, a fake is a working lightweight version (in-memory DB).
jest.fn()/vi.fn(): control it withmockReturnValue,mockReturnValueOnce,mockResolvedValue,mockImplementation. Inspect.mock.callsand.mock.results.spyOn(obj, 'method')keeps the real behaviour unless you override it, andmockRestore()puts the original back.jest.mock('./api')auto-mocks every export; pass a factory to control it. Jest's Babel plugin hoistsjest.mockabove imports, so the factory cannot use outer variables unless their names start withmock.vi.mockis also hoisted. Usevi.hoisted(() => ...)to create values the factory needs, andimportOriginalfor partial mocks.- Mock at the boundary (network, time, randomness, storage), not your own internal modules. Over-mocking tests your mocks, not your code.
Interview questions
- Difference between
jest.fn(),jest.spyOn()andjest.mock()? - Difference between
mockClear,mockResetandmockRestore? - Why can't a
jest.mockfactory use a variable defined at the top of the test file? - What are the dangers of over-mocking?
Fake timers & mocking the network (MSW)
Fake timers make time-based code instant and deterministic. MSW mocks HTTP at the request level so your real fetch code runs.
useFakeTimers()replacessetTimeout,setInterval,Dateand friends. Move time withadvanceTimersByTime(ms),runAllTimers()orrunOnlyPendingTimers(). Go back withuseRealTimers().- Use
runOnlyPendingTimersfor recursive timers (polling), becauserunAllTimerswould loop until it hits its limit. - Async helpers like
advanceTimersByTimeAsyncalso flush promises between timers, which matters when timers andawaitare mixed. - With user-event and fake timers, pass
userEvent.setup({ advanceTimers: vi.advanceTimersByTime }), otherwise its internal delays hang. - MSW (Mock Service Worker) defines handlers like
http.get('/api/user', () => HttpResponse.json({...})). In Node it intercepts requests; in the browser it uses a Service Worker. - Because MSW works at the network layer, the same handlers serve unit tests, Storybook and local development, and your real fetch/axios/React Query code is exercised.
Interview questions
- How do you test a debounced search input?
- Why do you prefer MSW over mocking
fetchor the API module? - Difference between
runAllTimersandrunOnlyPendingTimers?
Snapshot testing: pros & cons
A snapshot stores serialized output and fails when it changes. Cheap to write, easy to rubber-stamp.
toMatchSnapshot()writes a.snapfile on first run and compares on later runs.toMatchInlineSnapshot()writes the value into the test file itself.- Update intentionally changed snapshots with
jest -uorvitest -u(oruin watch mode). Review the diff in code review like any other code. - Good for: small, stable output such as serializers, error messages, generated config, CLI output or a compact AST.
- Bad for: large component trees. Big snapshots change on every markup tweak, so people press
-uwithout reading, and the test stops protecting anything. - Dynamic values (dates, random ids) break snapshots. Use property matchers like
expect.any(Date), fake time or custom serializers. - Visual regression (screenshots) is a different thing: it compares pixels, not serialized markup.
Interview questions
- What are the pros and cons of snapshot testing?
- A snapshot test fails after your change. What do you do?
- Snapshot testing vs visual regression testing?
Component testing
React Testing Library philosophy & queries
"The more your tests resemble the way your software is used, the more confidence they give you." Query by role and label, not by class or component internals.
- RTL renders into a real DOM (jsdom) and gives you DOM queries, not access to component state or instances. That keeps tests independent of implementation.
- Priority: accessible to everyone (
getByRole,getByLabelText,getByPlaceholderText,getByText,getByDisplayValue) → semantic (getByAltText,getByTitle) → test id (getByTestId). getByRole('button', { name: /save/i })matches the accessible name. If you cannot find an element by role, the UI may be inaccessible.- Use
screeninstead of destructuring fromrender. Usewithin(container)to scope queries to one region, like a table row. - Add
@testing-library/jest-domfor readable matchers:toBeInTheDocument,toBeVisible,toBeDisabled,toHaveValue,toHaveAccessibleName. - RTL cleans up after each test automatically when your runner exposes a global
afterEach(Jest, or Vitest withglobals: true).
Interview questions
- What is the guiding philosophy of React Testing Library?
- Difference between
getBy,queryByandfindBy? - Why is
getByRolethe preferred query and when do you usegetByTestId? - How does RTL differ from Enzyme?
user-event, async UI & testing hooks
Simulate real interactions with user-event, wait for async UI with findBy/waitFor, and test hooks through a component or renderHook.
fireEvent.clickdispatches one DOM event.user-eventsimulates a full interaction: pointer down/up, focus,click, key events and input events, and it respectsdisabledandpointer-events: none.- user-event v14: create
const user = userEvent.setup()before rendering, and await every call (await user.type(...)). waitFor(() => expect(...))retries the callback until it passes or times out. Put one assertion inside and no side effects.act()makes sure React has flushed updates and effects. RTL'srender, user-event and async utilities already wrap inact; an "not wrapped in act" warning usually means an update happened after the test finished.- Test a hook through a real component if possible. For reusable hooks use
renderHookfrom@testing-library/react(the old@testing-library/react-hookspackage is deprecated). - Hooks that need context (router, query client, store) get a
wrapperoption that renders the providers.
Interview questions
fireEventvsuserEvent: which do you use and why?- What does the "not wrapped in act(...)" warning mean?
- How do you test a custom hook?
E2E & test quality
E2E: Playwright vs Cypress
Both drive real browsers with auto-waiting. Playwright runs out of process with many browsers and parallel workers; Cypress runs inside the browser with a great interactive runner.
- Playwright (Microsoft) controls Chromium, Firefox and WebKit through a protocol from outside the page. It supports multiple tabs, origins and browser contexts, and runs tests in parallel workers by default.
- Locators (
page.getByRole('button', { name: 'Save' })) are lazy and re-resolve on every action, so they survive re-renders. Prefer role, label, text and test-id locators over CSS/XPath. - Auto-waiting: before
click, Playwright checks the element is attached, visible, stable, enabled and receives events. Web-first assertions likeawait expect(locator).toHaveText('Saved')retry until timeout (5 s by default). - Fixtures (
page,context,request, or custom viatest.extend) give each test an isolated, fresh setup. A browser context is like a new incognito profile, cheap to create. - Cypress runs your test code inside the browser next to the app. Commands are queued and retried;
cy.interceptstubs network calls. Its time-travel runner is great for debugging. - Debugging: Playwright trace viewer (
trace: 'on-first-retry'), UI mode and codegen; Cypress screenshots, videos and the interactive runner.
Interview questions
- Playwright vs Cypress: how would you choose?
- What is auto-waiting and why does it reduce flakiness?
- What are Playwright fixtures?
- How do you handle authentication in E2E tests?
Flaky tests & visual regression
A flaky test passes and fails on the same code. Find the race, fix the cause, and only use retries as a signal, not a cure.
- Common causes: fixed sleeps, assertions that do not retry, shared test data, test order dependency, animations, real network calls, time zones and dates, and too many parallel workers on a weak CI machine.
- Detect: run with
--repeat-each=20(Playwright) or loop the test locally; track tests that pass only on retry. Playwright reports them as "flaky". - Fix: wait for state (a response, text, URL), isolate data per test, mock third-party services, disable animations, and freeze the clock (
page.clock). - Quarantine a flaky test (tag and skip from the blocking job) with a ticket; don't leave it red-but-ignored, which teaches the team to ignore CI.
- Visual regression:
await expect(page).toHaveScreenshot()compares against a stored baseline with a pixel threshold. Hosted tools like Chromatic or Percy add a review UI, often on Storybook stories. - Baselines depend on OS, browser and fonts, so generate them in the same Docker image as CI. Mask dynamic areas (
mask: [locator]) and usemaxDiffPixelsorthresholdfor anti-aliasing noise.
Interview questions
- How do you deal with flaky E2E tests?
- How does visual regression testing work, and what are its pitfalls?
- Your test passes locally but fails in CI. What do you check?
Coverage metrics & TDD
Coverage tells you what code ran, not what was checked. TDD is a design loop: red, green, refactor.
- Four metrics: statements, branches (each side of
if,?:,&&,??), functions, lines. Branch coverage is the most informative. - Providers: Istanbul instruments the code with counters; V8 uses the engine's built-in coverage (faster, no instrumentation). Vitest supports both; Jest uses
coverageProvider: 'babel' | 'v8'. - Set thresholds (
coverageThresholdin Jest,coverage.thresholdsin Vitest) to stop coverage dropping, but don't make 100% a goal. People then write assertion-free tests. - Pitfalls: tests without assertions still give coverage; one-line
ifstatements count as covered lines even when only one branch ran; generated code and barrels skew numbers. - TDD: write a failing test (red), write the simplest code that passes (green), then clean up (refactor) with the test as a safety net.
- TDD works best for logic with clear inputs and outputs (parsers, reducers, validation, bug fixes). For exploratory UI, many teams write tests right after the spike instead.
Interview questions
- Is 100% code coverage a good goal?
- Difference between line and branch coverage?
- What is TDD and does it fit frontend work?
Packages & builds
npm vs Yarn vs pnpm, lockfiles, semver & scripts
Semver ranges say what may be installed; the lockfile says what was installed. Commit it and install from it in CI.
- Semver
MAJOR.MINOR.PATCH: major = breaking, minor = new features, patch = fixes.^1.2.3→>=1.2.3 <2.0.0;~1.2.3→>=1.2.3 <1.3.0. For0.x, caret locks the minor:^0.2.3→<0.3.0. - The lockfile (
package-lock.json,yarn.lock,pnpm-lock.yaml) records the exact resolved version and integrity hash of every package, including transitive ones, so installs are reproducible. npm cideletesnode_modulesand installs exactly from the lockfile; it fails ifpackage.jsonand the lockfile disagree. Equivalents:pnpm install --frozen-lockfile,yarn install --immutable.- pnpm stores each package version once in a global content-addressable store and hard-links it into projects. Its
node_modulesis symlinked and strict, so you cannot import packages you did not declare (phantom dependencies). dependenciesship with the app;devDependenciesare build/test tools;peerDependenciessay "the host app must provide this" (React for a component library).- Scripts:
npm run buildrunsscripts.buildwithnode_modules/.binon thePATH. npm runspre<name>/post<name>scripts automatically.npx/pnpm dlxrun a package binary without installing it globally.
Interview questions
- What is the difference between
^and~in package.json? - Why commit the lockfile, and what does
npm cido differently fromnpm install? - Why is pnpm faster and stricter than npm?
- Difference between dependencies, devDependencies and peerDependencies?
Bundlers: Webpack vs Vite vs esbuild, Rollup, Turbopack
A bundler follows imports from entry points, transforms each file and outputs optimised chunks. The tools differ in speed, dev model and plugin ecosystem.
- Why bundle at all: fewer requests, minification, tree shaking, code splitting, hashing for long-term caching, and transforms for TS, JSX and CSS.
- Webpack: very configurable through loaders (transform files) and plugins (hook into the build). Bundles the whole app even in dev. Unique features like Module Federation.
- Vite: dev server serves native ESM on demand; production uses a real bundler. Since Vite 8 (March 2026) both use Rolldown, a Rust bundler with a Rollup-compatible plugin API. Earlier versions used esbuild in dev and Rollup for builds.
- esbuild (Go) is extremely fast at transforming and bundling, but has a smaller plugin API and limited control over chunking. Often used inside other tools.
- Rollup produces clean, flat ESM output and pioneered tree shaking; it is the usual choice for libraries. Rolldown is its Rust successor.
- Turbopack (Rust, by Vercel) is the incremental bundler for Next.js and is the default there in recent versions. Rspack is a Rust Webpack-compatible alternative.
Interview questions
- What is the difference between a loader and a plugin in Webpack?
- Webpack vs Vite: why is Vite faster in development?
- Why do we still bundle for production if browsers support ES modules?
- What is Module Federation?
How the Vite dev server works
Vite serves your source as native ES modules, transforms each file on request, pre-bundles dependencies once, and pushes HMR updates over a WebSocket.
- On start, Vite scans for bare imports (
react,lodash-es) and pre-bundles dependencies intonode_modules/.vite/deps. This converts CommonJS to ESM and merges packages with hundreds of internal files into one module. - The browser loads
index.html, which has<script type="module" src="/src/main.tsx">. Eachimportbecomes an HTTP request that Vite handles on demand. - For each source file Vite runs the plugin pipeline: resolve, load, transform (TS/JSX stripped, CSS turned into a JS module that injects styles), and rewrites bare imports to
/node_modules/.vite/deps/react.js?v=hash. - Caching: pre-bundled deps get strong cache headers (
max-age=31536000, immutable); source files use conditional requests (304 Not Modified). - HMR: on file save Vite finds the module in its module graph, walks up to the nearest HMR boundary (a module that accepts updates, like a React component with Fast Refresh) and sends a WebSocket message. The browser re-imports only that module with a timestamp query.
- Vite does not type-check. Run
tsc --noEmit(orvue-tsc) in a separate process or in CI. Env vars exposed to the client must start withVITE_and are read withimport.meta.env.
Interview questions
- Explain how Vite's dev server works.
- Why does Vite pre-bundle dependencies?
- How does HMR keep component state?
Tree shaking & code splitting
Tree shaking removes exports nobody imports. Code splitting moves code that is not needed yet into chunks loaded later.
- Tree shaking (dead-code elimination for modules) works because ESM
import/exportare static: the bundler can see which exports are used without running the code. CommonJSrequireis dynamic, so it is hard to shake. - The bundler marks unused exports, then the minifier (Terser, esbuild, Oxc) drops them. Code with side effects at module top level must stay.
"sideEffects": falsein a library'spackage.jsonpromises that unused modules can be dropped entirely. List files that do have effects, such as["*.css", "./src/polyfills.js"]./*#__PURE__*/before a call tells the minifier that the call has no side effects, so it can be removed if the result is unused.- Code splitting: each dynamic
import()becomes a separate chunk loaded on demand. In React:const Page = lazy(() => import('./Page'))inside<Suspense>. Split by route first. - Bundlers also split shared/vendor chunks so common code is cached once. Too many tiny chunks hurt too: aim for a few meaningful chunks and prefetch likely next routes.
Interview questions
- What is tree shaking and what prevents it?
- What is code splitting and how do you decide where to split?
- What does
"sideEffects": falsedo?
Babel vs SWC vs tsc, and source maps
Transpilers turn modern TS/JSX into JS the target can run. Source maps map that output back to your original code.
- Babel (JS) is the most pluggable transpiler: presets (
@babel/preset-env,preset-react,preset-typescript) and custom plugins. It is slower than native tools. - SWC (Rust) and esbuild (Go) do the same job much faster. Next.js uses SWC; Vite uses esbuild up to v7 and Oxc from v8. Oxc is a newer Rust toolchain (parser, transformer, linter).
tscis the only one that type-checks. The fast tools transpile each file alone and just strip types, so setisolatedModules: trueto forbid TS features that need cross-file information.- Common setup: a fast transpiler in the bundler, plus
tsc --noEmitin CI and the editor for types. - Browserslist (
browserslistin package.json) tells tools which browsers to support; syntax is down-levelled to that target. Missing APIs need polyfills (core-js), not just syntax transforms. - Source maps (
.mapfiles) link generated positions to original file, line and column. The bundle ends with//# sourceMappingURL=app.js.map. In production, use hidden source maps uploaded to an error tracker like Sentry, so users cannot download them.
Interview questions
- Babel vs SWC vs tsc: what does each do?
- What is a source map and how does it work?
- Should you ship source maps to production?
- Why does
isolatedModulesmatter?
Code quality, monorepos & CI
ESLint & Prettier
ESLint finds bugs and bad patterns; Prettier only formats. Let Prettier own formatting and turn off ESLint's style rules.
- ESLint parses code into an AST and runs rules on it: unused variables,
no-undef, React hook rules (react-hooks/rules-of-hooks,exhaustive-deps), accessibility (jsx-a11y), and import rules. - ESLint 9 uses flat config (
eslint.config.js) by default: an array of config objects. The legacy.eslintrcformat is deprecated. - Prettier is an opinionated formatter: it reprints code from the AST with few options, which ends style debates in code review.
- Use
eslint-config-prettierto disable ESLint rules that conflict with Prettier. Run Prettier separately rather than as an ESLint rule; it is faster and the output is clearer. - Run on commit with husky + lint-staged (only staged files), and in CI with
eslint . --max-warnings=0andprettier --check .. typescript-eslintadds TS-aware rules; type-aware rules (likeno-floating-promises) need type information and are slower but catch real bugs. Biome and oxlint are fast Rust alternatives.
Interview questions
- What is the difference between ESLint and Prettier?
- How do you enforce code quality across a team?
- What is ESLint flat config?
Monorepos: workspaces, Turborepo & Nx
Workspaces link local packages together; Turborepo and Nx add a task graph, caching and "only build what changed".
- A monorepo holds many apps and packages (web, admin, ui-kit, utils) in one repo, with atomic cross-package changes and one set of tooling.
- Workspaces (npm, Yarn, pnpm) install all packages together and symlink local packages, so
apps/webcan depend on"@acme/ui": "workspace:*"(pnpm/Yarn protocol) without publishing. - Turborepo reads
turbo.jsontasks."dependsOn": ["^build"]means "build my dependencies first". It hashes inputs (files, env, lockfile) and caches outputs locally or remotely, so unchanged tasks are replayed instantly. - Nx does the same plus a richer project graph,
nx affectedto run only projects touched by a change, code generators and module-boundary lint rules. - Versioning and publishing: Changesets collects change notes per PR and bumps versions and changelogs for published packages.
- Costs: tooling complexity, slower installs and CI without caching, and the need for clear ownership (CODEOWNERS) and boundaries between packages.
Interview questions
- Monorepo vs polyrepo: trade-offs?
- How does Turborepo make builds faster?
- What does
workspace:*mean?
CI for frontend projects
A good pipeline is fast, reproducible and gives clear signals: install from the lockfile, run cheap checks first, parallelise tests, and keep artifacts for debugging.
- Typical order: install (frozen lockfile, cached) → lint + format check + type-check → unit/integration tests with coverage → build → E2E against a preview build → deploy preview.
- Speed: cache the package manager store (
actions/setup-nodewithcache: pnpm), cache Playwright browsers, use Turborepo/Nx remote cache, and run only affected projects on PRs. - Shard slow suites across machines:
playwright test --shard=1/4,vitest --shard=1/4, then merge reports. - Install E2E browsers with
npx playwright install --with-deps, or use the official Playwright Docker image for stable fonts and screenshots. - Upload artifacts on failure: Playwright HTML report and traces, coverage reports, bundle stats. Post a preview deployment URL on each PR.
- Guardrails: required status checks, bundle size budgets (size-limit, Lighthouse CI), dependency audits and automated updates (Dependabot, Renovate), and secrets kept in the CI store, never in the repo.
Interview questions
- Design a CI pipeline for a React app.
- How would you speed up a slow frontend CI?
- How do you catch bundle-size or performance regressions in CI?