Testing And QA Flashcards
(10 cards)
What is the difference between unit and integration testing?
Unit testing tests individual functions/components in isolation; integration testing tests interactions between components. Example: Test a React component (unit) vs. API call with database (integration).
How do you write a unit test for a JavaScript function using Jest?
```javascript
function add(a, b) { return a + b; }
test(‘adds 2 + 3 to equal 5’, () => {
expect(add(2, 3)).toBe(5);
});
// Explanation: Jest tests function output, ensuring correctness (O(1)).
~~~
What is mocking, and why is it used in testing?
Mocking simulates dependencies (e.g., APIs) to isolate tests. Example: Mock fetch
in Jest to test a React component without hitting a real API, improving speed and reliability.
How do you test a React component with Jest and React Testing Library?
```javascript
import { render, screen } from ‘@testing-library/react’;
import Button from ‘./Button’;
test(‘renders button with text’, () => {
render(<button>Click</button>);
expect(screen.getByText(‘Click’)).toBeInTheDocument();
});
// Explanation: Tests UI rendering, ensuring button displays text.
~~~
What is end-to-end (E2E) testing, and when is it used?
E2E testing simulates user workflows across the app. Example: Use Cypress to test a login flow from frontend to backend. Used to verify full system functionality.
How do you write an E2E test with Cypress for a login form?
```javascript
describe(‘Login’, () => {
it(‘submits credentials’, () => {
cy.visit(‘/login’);
cy.get(‘input[name=username]’).type(‘user’);
cy.get(‘input[name=password]’).type(‘pass’);
cy.get(‘button’).click();
cy.url().should(‘include’, ‘/dashboard’);
});
});
// Explanation: Simulates user login, checks navigation.
~~~
What is test coverage, and why does it matter?
Test coverage measures the percentage of code executed by tests. Example: Aim for 80% coverage with Jest (--coverage
). Ensures critical paths are tested, but 100% isn’t always practical.
How do you test an Express API endpoint?
```javascript
const request = require(‘supertest’);
const app = require(‘./app’);
test(‘GET /users returns user list’, async () => {
const res = await request(app).get(‘/users’);
expect(res.status).toBe(200);
expect(res.body).toHaveLength(2);
});
// Explanation: Uses supertest to test API response (O(1)).
~~~
What is the Arrange-Act-Assert pattern in testing?
Arrange sets up test data; Act calls the function/component; Assert verifies results. Example: Arrange let x = 2;
, Act let sum = add(x, 3);
, Assert expect(sum).toBe(5);
.
How do you ensure tests run fast in a large codebase?
Use in-memory databases (e.g., SQLite), mock external services, and run tests in parallel with Jest’s --runInBand
. Example: Mock MongoDB with mongodb-memory-server
.