Facebook Pixel

How do you mock functions in Jest?

Use jest.mock('../module') to replace a module with a mock, then use mockResolvedValue or mockImplementation to control the return. Use jest.spyOn(object, 'method') to spy on existing functions. Use mockRestore() to restore the original.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Node.js Testing Interview Questions Jest, Supertest, and Testing Best Practices

Unit tests (individual functions in isolation), integration tests (components working together), end-to-end tests (full application flow), performance tests (speed and scalability), and security tests (vulnerabilities). Unit tests are fast and numerous, E2E tests are slow and few.

Use Jest as the test runner and Supertest for HTTP requests. Import the Express app, use request(app).post('/api/signup').send({...}), and assert on the response status, body, and headers. Supertest doesn't require the server to be running it calls the Express app directly.

Use mongodb-memory-server to create an in-memory MongoDB instance. Connect in beforeAll, clean collections in afterEach (deleteMany({})), and disconnect in afterAll. This ensures tests are isolated, fast, and don't affect your development database.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.