Jest, Vitest & Testing Library Interview Questions Hindi mein

Jest, Vitest & Testing Library कोर्स के 25 सवाल, हर सवाल के सही जवाब और explanation के साथ। जवाब देखने से पहले ख़ुद सोचें।

Testing Foundations

1. What does the testing trophy emphasise most for frontend apps?

  1. Snapshot tests of every component
  2. Only end-to-end tests in a real browser
  3. Integration tests that exercise several units together
  4. Unit tests of private helper functions only
जवाब देखें

जवाब: Integration tests that exercise several units together

Integration tests give a good balance of confidence and speed.

पाठ: Why Automated Tests and Which Kinds

2. Why is Vitest a natural fit for a Vite project?

  1. It reuses the Vite config, plugins and aliases and handles TypeScript and ESM out of the box
  2. It is the only runner that supports snapshots
  3. It runs tests in a real browser by default
  4. It does not need assertions
जवाब देखें

जवाब: It reuses the Vite config, plugins and aliases and handles TypeScript and ESM out of the box

Vitest shares the build pipeline the app already uses.

पाठ: Jest Versus Vitest

3. Why do component tests need jsdom or happy-dom?

  1. They replace the assertion library
  2. They make tests run in Chrome
  3. They compile TypeScript
  4. The default node environment has no document or window for components to render into
जवाब देखें

जवाब: The default node environment has no document or window for components to render into

A simulated DOM is what rendering and querying need.

पाठ: Setting Up Jest or Vitest

Writing Good Tests

4. What does arrange-act-assert describe?

  1. Write the assertion first and the code never
  2. Set up inputs, perform one action, then check the observable result
  3. Run the test three times to confirm
  4. Mock every dependency before writing code
जवाब देखें

जवाब: Set up inputs, perform one action, then check the observable result

A consistent shape makes tests easy to read.

पाठ: describe, it and Arrange-Act-Assert

5. Why does expect(fn()).toThrow() usually fail to catch the error?

  1. toThrow only works with async code
  2. fn() runs and throws before expect receives anything; toThrow needs a function to call
  3. toThrow only accepts strings
  4. Errors are always swallowed by the runner
जवाब देखें

जवाब: fn() runs and throws before expect receives anything; toThrow needs a function to call

Wrap the call: expect(() => fn()).toThrow().

पाठ: Choosing the Right Matcher

6. A test passes alone but fails when the whole file runs. What is the most likely cause?

  1. The file has too many describe blocks
  2. The test name is too long
  3. toEqual is slower than toBe
  4. State leaking between tests, such as a shared object or an unrestored mock
जवाब देखें

जवाब: State leaking between tests, such as a shared object or an unrestored mock

Tests must be independent of order.

पाठ: Setup, Teardown and Test Isolation

Async Code and Time

7. What happens if you forget await before expect(p).rejects.toThrow()?

  1. The test can finish and pass before the assertion is checked
  2. The runner automatically awaits it
  3. TypeScript refuses to compile
  4. The promise is cancelled
जवाब देखें

जवाब: The test can finish and pass before the assertion is checked

Always await or return async assertions.

पाठ: Testing Promises and async/await

8. What does vi.advanceTimersByTime(500) do under fake timers?

  1. Sets a 500 ms timeout on the test
  2. Sleeps the test for 500 ms of real time
  3. Moves the fake clock 500 ms forward and runs any callbacks that became due
  4. Skips the next 500 tests
जवाब देखें

जवाब: Moves the fake clock 500 ms forward and runs any callbacks that became due

Time only moves when the test says so.

पाठ: Fake Timers

9. Which approach makes a date-dependent function easiest to test?

  1. Use real timers and retry on failure
  2. Run the tests only at midnight
  3. Pass the current time in as a parameter with a sensible default
  4. Snapshot the output of new Date()
जवाब देखें

जवाब: Pass the current time in as a parameter with a sensible default

Injected time needs no global mocks.

पाठ: Dates and Randomness

Mocks, Spies and the Network

10. What does vi.spyOn(console, "warn") do by default?

  1. Wraps console.warn so calls are recorded while the original still runs
  2. Deletes console.warn
  3. Silences all console output globally forever
  4. Turns warnings into test failures
जवाब देखें

जवाब: Wraps console.warn so calls are recorded while the original still runs

Override with mockImplementation if you want it silent.

पाठ: Mock Functions and Spies

11. Why can a vi.mock factory not use a normal const declared above it?

  1. Constants are frozen by Vitest
  2. Factories may only return strings
  3. Mocks run in a separate browser
  4. vi.mock is hoisted above the declarations, so the variable is not initialised yet
जवाब देखें

जवाब: vi.mock is hoisted above the declarations, so the variable is not initialised yet

Use vi.hoisted (or the mock prefix in Jest).

पाठ: Module Mocking and Hoisting

12. What is the main advantage of MSW over mocking fetch directly?

  1. It makes real calls to production
  2. Your real request code runs and tests do not depend on which HTTP client you use
  3. It removes the need for async tests
  4. It only works with GraphQL
जवाब देखें

जवाब: Your real request code runs and tests do not depend on which HTTP client you use

Mock the network, not the client.

पाठ: Mocking the Network with MSW

Testing Library Principles

13. Which assertion best follows the Testing Library principle?

  1. The component state field isSubmitted equals true
  2. A success message becomes visible after submitting the form
  3. A div has the class form--submitted
  4. The submit handler was defined with useCallback
जवाब देखें

जवाब: A success message becomes visible after submitting the form

Assert on what the user can perceive.

पाठ: Test Behaviour, Not Implementation

14. Which query does Testing Library recommend trying first for a Save button?

  1. getByTitle('Save')
  2. getByTestId('save-btn')
  3. container.querySelector('.btn-save')
  4. getByRole('button', { name: 'Save' })
जवाब देखें

जवाब: getByRole('button', { name: 'Save' })

Role plus accessible name matches how users and assistive tech find it.

पाठ: Query Priority

15. Which variant should you use to wait for text that appears after a fetch?

  1. findByText, which returns a promise that retries until it appears
  2. getByText, which throws immediately
  3. queryByText, which returns null
  4. getAllByText inside a setTimeout
जवाब देखें

जवाब: findByText, which returns a promise that retries until it appears

find* combines get* with waiting.

पाठ: get, query and find Variants

Testing React Components

16. Where does @testing-library/jest-dom fit in?

  1. It replaces jsdom
  2. It renders React components
  3. It adds DOM-specific matchers like toBeInTheDocument and toBeDisabled
  4. It mocks network requests
जवाब देखें

जवाब: It adds DOM-specific matchers like toBeInTheDocument and toBeDisabled

Load it once in the setup file.

पाठ: Rendering Components

17. How should user-event v14 interactions be called?

  1. Wrap every call in setTimeout
  2. Call userEvent.click synchronously and never await
  3. Create user = userEvent.setup() and await each call such as await user.click(button)
  4. Only through fireEvent
जवाब देखें

जवाब: Create user = userEvent.setup() and await each call such as await user.click(button)

The v14 API is asynchronous.

पाठ: User Interactions with user-event

18. What should go inside a waitFor callback?

  1. An assertion that will eventually pass, with no side effects such as clicks
  2. A user.click call so it retries the click
  3. A fixed sleep of 2 seconds
  4. The render call
जवाब देखें

जवाब: An assertion that will eventually pass, with no side effects such as clicks

waitFor may run the callback many times.

पाठ: Async UI, Forms and Hooks

Snapshots, Providers and Coverage

19. When is a snapshot test most useful?

  1. For values that include the current timestamp
  2. For the full HTML of every page
  3. As a replacement for all assertions
  4. For a small, stable serialised output that reviewers can actually read
जवाब देखें

जवाब: For a small, stable serialised output that reviewers can actually read

Keep snapshots small and intentional.

पाठ: Snapshot Testing and When to Avoid It

20. Why create a new QueryClient (or store) inside the custom render?

  1. Because providers cannot be reused in production
  2. So cached data and state do not leak from one test into another
  3. To make tests run in a real browser
  4. To increase coverage numbers
जवाब देखें

जवाब: So cached data and state do not leak from one test into another

Fresh state per test keeps tests isolated.

पाठ: Context, Providers and Routing

21. What does 100% line coverage guarantee?

  1. The code has no bugs
  2. Every line ran during the tests, not that its behaviour was checked
  3. Every branch and edge case was asserted
  4. The UI is accessible
जवाब देखें

जवाब: Every line ran during the tests, not that its behaviour was checked

Coverage measures execution, not verification.

पाठ: Coverage and Its Limits

Test Suites in Practice and CI

22. What is the main benefit of a test data factory with overrides?

  1. It replaces MSW handlers
  2. It removes the need for assertions
  3. It makes data random on every run
  4. Tests specify only the fields they care about while still getting valid objects
जवाब देखें

जवाब: Tests specify only the fields they care about while still getting valid objects

Defaults plus overrides keep tests short and explicit.

पाठ: Organising Tests and Test Data Factories

23. Which is a common cause of flaky component tests?

  1. Waiting with a fixed sleep instead of awaiting findBy or waitFor
  2. Using getByRole instead of getByTestId
  3. Writing tests in TypeScript
  4. Having a setup file
जवाब देखें

जवाब: Waiting with a fixed sleep instead of awaiting findBy or waitFor

Wait for the condition, not for time.

पाठ: Flaky Tests and Debugging

24. What does --shard=2/4 do?

  1. Runs only tests with "2" in the name
  2. Runs each test four times
  3. Runs the second quarter of the test files so four jobs can split the suite
  4. Uses two workers on four CPUs
जवाब देखें

जवाब: Runs the second quarter of the test files so four jobs can split the suite

Sharding splits work across machines.

पाठ: Running Tests in CI

25. Which item belongs on a healthy frontend testing checklist?

  1. Tests rely on fixed sleeps for async UI
  2. Every component has a full-page snapshot
  3. Network calls are mocked with MSW and unhandled requests fail the test
  4. Coverage must be exactly 100%
जवाब देखें

जवाब: Network calls are mocked with MSW and unhandled requests fail the test

Deterministic, behaviour-focused, boundary-mocked tests.

पाठ: A Frontend Testing Checklist

← कोर्स पर वापस जाएँ