Lesson 1 · Unit 01
Assertions
A test is a claim a machine can check
What you practise
- Arrange, act, assert
- One behaviour per test
- Reading a failure message
- Test names that say what broke
- Tests as executable examples
Try a question from this lesson
Pick one
Someone claims this returns a price after a 10% discount. Which call proves the claim wrong?
def discounted(price):
return price - 10function discounted(price) {
return price - 10;
}function discounted(price: number) {
return price - 10;
}Hint
Work out 10% of each input, then what the function subtracts.
Correct answer
discounted(50)
Why
For 100 the bug hides: 10% of 100 happens to be 10. For 50 the function returns 40, not 45. A test is a claim plus an input that could prove it wrong.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Arrange, act, assert
A test is a small function that makes a claim and checks it.
Arrange: build the input. Act: call the code under test. Assert: state what must be true.
If the claim is false, the assertion raises an error and the test fails. No error means it passed.
def test_ten_percent_off():
price = 50 # arrange
got = discounted(price) # act
assert got == 45 # assertfunction assertEqual(got, want) {
if (got !== want) {
throw new Error("not equal");
}
}
function testTenPercentOff() {
const price = 50; // arrange
const got = discounted(price); // act
assertEqual(got, 45); // assert
}function assertEqual(
got: unknown,
want: unknown,
): void {
if (got !== want) {
throw new Error("not equal");
}
}
function testTenPercentOff(): void {
const price = 50; // arrange
const got = discounted(price); // act
assertEqual(got, 45); // assert
}Python noteassert x raises AssertionError when x is false. Runners like pytest find every function named test_... and call it for you.
JavaScript noteJavaScript has no assert keyword, so tests call a helper. Node ships one: assert.strictEqual(got, want). From here on, assume assertEqual exists and also compares arrays item by item.
TypeScript noteunknown accepts any value but, unlike any, lets you do nothing with it until you check it. !== is fine on anything. From here on, assume assertEqual exists and compares arrays item by item.
10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.