What is a unit test? How do you know a test you wrote actually works?
Suggested answer
A unit test automatically checks a small piece of code (a function, a module): given this input, the result must be that. It runs fast and needs no server or database, so you can run it every time you save a file and before every merge.
The second half of the question is the part the interviewer really wants to hear. A test works when it turns red when the code is wrong. A few signs worth mentioning:
- The expected result comes from outside the code. Write
expect(orderTotal(order)).toBe(70000)because you know 2 coffees × 35,000 is 70,000. Don't recompute the expected value with the same formula you're testing, because then the test compares the code with itself and is always green. - Break the code on purpose. After fixing a bug, temporarily remove the fix and run the test again. If it's still green, it isn't checking the right thing.
- Include the cases that must be rejected, not only the ones that work. For example, a price parser should throw on
"35,000"instead of guessing. - The test name tells you what it protects, like "2 salt coffees at 35,000 cost 70,000", so whoever turns it red understands straight away without asking.
Bonus points: say that tests for each small function aren't enough. You also want a test that goes through the real data path (read raw data → normalize → total), because bugs often hide where a function is correct but no longer gets called.