🌍 ReactJS · subject

ReactJS Testing in React Syllabus

The Testing in React syllabus for ReactJS in full: 3 chapters and 9 topics, every one listed below, plus 51 Testing in React flashcards with answers.

3Chapters
9Topics
51Flashcards

Testing in React syllabus: all 3 chapters

Expand any chapter to see its topics and sub-topics.

  1. Unit Testing

    3 topics
    • Setting Up Jest
    • Writing Unit Tests
    • Testing Components
  2. Integration Testing

    3 topics
    • Setting Up Testing Library
    • Writing Integration Tests
    • Testing User Interactions
  3. End-to-End Testing

    3 topics
    • Setting Up Cypress
    • Writing End-to-End Tests
    • Running Tests in CI/CD

ReactJS Testing in React flashcards — 51 questions with answers

  1. What is Jest?

    Jest is a JavaScript testing framework maintained by Meta that provides a test runner, assertion library, mocking utilities, and code-coverage reporting in a single zero-config package.

  2. Which command installs Jest as a development dependency in an npm project?

    npm install --save-dev jest

  3. In package.json, how do you configure the standard script to run Jest?

    Add "scripts": { "test": "jest" } so that running npm test invokes Jest.

  4. By default, which file naming patterns does Jest treat as test files?

    Files ending in .test.js or .spec.js, and any file located inside a __tests__ directory.

  5. What is the purpose of a jest.config.js file?

    It centralizes Jest configuration (test environment, module mappers, setup files, coverage settings, transforms) so options don't have to be passed on the command line.

  6. For testing React components that touch the DOM, which Jest testEnvironment must be set?

    testEnvironment: 'jsdom' (jsdom simulates a browser DOM in Node); in older Jest it was the default, but Jest 27+ defaults to 'node'.

  7. Which Babel or transform tooling lets Jest understand JSX and modern ES syntax?

    babel-jest together with @babel/preset-env and @babel/preset-react (configured via babel.config.js), or ts-jest for TypeScript.

  8. What is the difference between the Jest globals describe() and test()/it()?

    describe() groups related tests into a block (a test suite), while test() (aliased it()) defines an individual test case containing assertions.

  9. What is a unit test?

    A unit test verifies the smallest testable piece of code (a single function, module, or component) in isolation from its dependencies, confirming it behaves correctly for given inputs.

  10. What is the standard three-part structure (pattern) for organizing the body of a unit test?

    Arrange-Act-Assert (AAA): arrange the inputs/state, act by invoking the code under test, then assert the expected outcome.

  11. In Jest, what does the expect() function return and how is it used?

    expect(value) wraps the actual value and returns an 'expectation' object exposing matcher methods (e.g., .toBe, .toEqual) that assert conditions about it.

  12. What is the difference between the Jest matchers toBe() and toEqual()?

    toBe() checks strict referential/primitive equality (Object.is), while toEqual() recursively checks structural (deep) value equality of objects and arrays.

  13. Which Jest matcher asserts that a function throws an error when called?

    expect(() => fn()).toThrow() — the code under test must be wrapped in a function so Jest can invoke it and catch the error.

  14. How do you assert the opposite of a matcher in Jest?

    Chain .not before the matcher, e.g., expect(value).not.toBe(5).

  15. What is a mock function in Jest and how do you create one?

    A mock function records calls, arguments, and return values so you can assert on interactions; create one with jest.fn(), optionally giving it an implementation or return value.

  16. What does jest.mock('module-path') do?

    It automatically replaces the specified module with an auto-mocked version whose functions are jest.fn() stubs, isolating the unit under test from that dependency.

  17. What is the purpose of the beforeEach() and afterEach() hooks in Jest?

    beforeEach() runs setup code before every test in scope and afterEach() runs teardown after every test, ensuring each test starts from a clean, consistent state.

  18. How do you run a single test or focus on a subset in Jest?

    Use test.only() / describe.only() to run only that block, or test.skip() to skip; from the CLI use jest -t 'name pattern'.

  19. What flag makes Jest generate a code-coverage report?

    jest --coverage, which outputs statement, branch, function, and line coverage percentages.

  20. What is a snapshot test in Jest?

    A snapshot test serializes a component's rendered output (or any value) with expect(...).toMatchSnapshot(), stores it on first run, and fails future runs if the output differs from the saved snapshot.

Show the other 31 Testing in React flashcards
  1. What is React Testing Library (RTL)?

    React Testing Library is a lightweight library for testing React components by interacting with the rendered DOM the way a user would, rather than testing implementation details like state or instance methods.

  2. Which packages do you install to use React Testing Library with Jest?

    @testing-library/react, @testing-library/jest-dom (custom DOM matchers), and @testing-library/user-event for realistic interactions.

  3. What is the guiding philosophy of React Testing Library?

    "The more your tests resemble the way your software is used, the more confidence they give you" — test behavior via the DOM, not implementation details.

  4. What does the @testing-library/jest-dom package add, and how is it enabled?

    It adds DOM-specific matchers like toBeInTheDocument(), toHaveTextContent(), and toBeDisabled(); enable it by importing '@testing-library/jest-dom' in a Jest setupFilesAfterEach/setup file.

  5. What does the render() function from React Testing Library do?

    It renders a React element into a container attached to document.body and returns query utilities plus helpers (rerender, unmount) for interacting with the output.

  6. What is the recommended query priority order in React Testing Library?

    Prefer accessible queries first: getByRole, then getByLabelText/getByPlaceholderText/getByText, then getByDisplayValue/getByAltText/getByTitle, and use getByTestId only as a last resort.

  7. What is the difference between getBy, queryBy, and findBy queries in RTL?

    getBy throws if no match (sync), queryBy returns null if absent (sync, for asserting non-existence), and findBy returns a Promise that resolves when the element appears (async, for awaited elements).

  8. When would you use the getAllBy* variant of a Testing Library query?

    When multiple elements match the query; getAllBy* returns an array and throws if none are found, whereas the singular getBy* throws if more than one matches.

  9. What is an integration test?

    An integration test verifies that multiple units/components work together correctly, exercising their combined behavior and the interfaces between them rather than each unit in isolation.

  10. How does an integration test differ from a unit test in scope?

    A unit test isolates one piece with dependencies mocked; an integration test lets several real units interact (e.g., a form component with its child inputs and a context provider) to catch interface and wiring bugs.

  11. In RTL, how do you wait for an assertion to pass after an asynchronous update?

    Wrap it in await waitFor(() => expect(...).toBe...); waitFor retries the callback until it passes or times out.

  12. What is the screen object in React Testing Library and why is it preferred?

    screen is a global object bound to document.body exposing all queries (screen.getByRole, etc.); it's preferred because you don't have to destructure queries from render, keeping tests consistent.

  13. How do you provide React context or a router to a component under integration test?

    Pass a wrapper option to render, e.g., render(<Child />, { wrapper: ({children}) => <Provider>{children}</Provider> }), or wrap the element directly in the provider/router.

  14. What is the @testing-library/user-event library and how does it differ from fireEvent?

    user-event simulates full user interactions (focus, keydown, keyup, input) more realistically, while fireEvent dispatches a single low-level DOM event; user-event is preferred for accurate behavior.

  15. How do you simulate a user clicking a button with user-event (v14+)?

    const user = userEvent.setup(); then await user.click(screen.getByRole('button', { name: /submit/i })); — user-event methods return Promises and must be awaited.

  16. How do you type text into an input field using user-event?

    await user.type(screen.getByRole('textbox'), 'hello'); which fires keyboard events character by character to update the input value.

  17. After firing a user interaction, how do you assert that a handler prop was called?

    Pass a jest.fn() as the handler prop, trigger the interaction, then assert expect(handler).toHaveBeenCalledTimes(1) and/or toHaveBeenCalledWith(expectedArgs).

  18. Why must state updates from interactions be wrapped in act() (and how does RTL handle it)?

    React requires state updates to occur inside act() so effects flush before assertions; RTL's render, fireEvent, and user-event already wrap updates in act(), so manual act() is rarely needed.

  19. What is Cypress?

    Cypress is a JavaScript end-to-end and component testing framework that runs tests directly in a real browser, offering automatic waiting, time-travel debugging, and a visual test runner.

  20. Which command installs Cypress as a dev dependency, and which opens its interactive runner?

    Install with npm install --save-dev cypress; open the GUI runner with npx cypress open, or run headlessly with npx cypress run.

  21. Where does Cypress place end-to-end test (spec) files by default, and what extension do they use?

    In the cypress/e2e directory, using the .cy.js (or .cy.ts) extension.

  22. What is the purpose of the cypress.config.js file?

    It configures Cypress project settings such as baseUrl, viewport size, environment variables, timeouts, and e2e/component testing setup nodes.

  23. What is an end-to-end (E2E) test?

    An E2E test validates a complete user workflow through the whole running application—UI, network, and backend—simulating real user actions from start to finish in a browser.

  24. How do you visit a page and click a link in a Cypress E2E test?

    cy.visit('/'); then cy.get('a.nav-link').click(); Cypress automatically waits for the element to be actionable before clicking.

  25. How does Cypress reduce test flakiness compared to older tools like Selenium?

    Cypress automatically retries commands and assertions with built-in waiting until elements exist and are actionable, so you rarely need explicit sleeps/waits.

  26. Which Cypress command types text into an input, and which asserts on an element?

    cy.get(selector).type('text') types input; assertions use cy.get(selector).should('have.text', 'value') or .should('be.visible').

  27. How do you stub or intercept a network request in Cypress?

    Use cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers'); then cy.wait('@getUsers') to control and await the response.

  28. What is the testing pyramid and what does it recommend?

    The testing pyramid recommends many fast, cheap unit tests at the base, fewer integration tests in the middle, and a small number of slow, expensive end-to-end tests at the top.

  29. What does CI/CD stand for, and why run tests in it?

    Continuous Integration / Continuous Delivery (or Deployment); running the test suite automatically on every push/PR catches regressions early and gates broken code from being merged or released.

  30. How do you run Jest non-interactively in a CI environment?

    Run jest --ci (often with --watchAll=false and --coverage); the --ci flag disables snapshot writing for new snapshots so unexpected snapshots fail instead of being created.

  31. In a GitHub Actions workflow, what are the typical steps to run a React project's tests?

    Check out the code (actions/checkout), set up Node (actions/setup-node), install dependencies (npm ci), then run the tests (npm test -- --ci or npx cypress run).

ReactJS Testing in React FAQ

What is in the ReactJS Testing in React syllabus?

ReactJS Testing in React is split into 3 chapters: Unit Testing, Integration Testing and End-to-End Testing. Together they contain 9 topics.

How many chapters are in ReactJS Testing in React?

3 chapters, containing 9 topics. The largest chapter is Unit Testing, with 3 topics.

Are there flashcards for ReactJS Testing in React?

Yes — a 51-card Testing in React deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.