Lesson 7.1Lesson 24 of 24
Effective unit tests
With a block of code and the associated Unit Test, determine where the test is ineffective and modify it to make it more effective.
Key points
- 1A good test fails when the behaviour breaks. Assert the exact expected value, not just that something is truthy or that no error was thrown.
- 2Each test sets up its own data. A test that passes only after another test has run is not isolated.
- 3Replace the clock, random numbers and network with values you control, so the result is the same on every run.
- 4Stub or spy on dependencies, never on the code under test. Assert results and outgoing calls, not private fields.
- 5An async test must wait for its assertions: return the promise or await it, including assert.rejects.
What the exam guide checks here
Objective wording from the exam guide (English).
- 7.1.K1What makes a unit test effective: isolated, deterministic, one behaviour, meaningful assertions
- 7.1.K2Test doubles: stubs, spies and mocks; testing asynchronous code
- 7.1.S1Find why a given test passes without proving the behaviour, and fix it
Lock it in
Answer scenario questions on this topic. Every option comes with an explanation.
Practise 7.1 · 12 questions