From 7810c04512ec08f491310a22cde951d764178f5f Mon Sep 17 00:00:00 2001 From: Ali Mohammad Date: Tue, 23 May 2023 23:27:39 +0300 Subject: [PATCH] Update first_rule.md --- testing/first_rule.md | 62 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/testing/first_rule.md b/testing/first_rule.md index dde593e..230dd37 100644 --- a/testing/first_rule.md +++ b/testing/first_rule.md @@ -11,4 +11,64 @@ Clean tests should follow the rules: - **Self-Validating** a test should answer with either _Passed_ or _Failed_. You don't need to compare log files to answer if a test passed. - **Timely** unit tests should be written before the production code. If you write tests after the production code, you might find writing tests too hard. - + +** Good + +```typescript +// add.ts + +export const add = (a: number, b: number): number => { + return a + b; +}; + +// add.test.ts + +import { add } from './add'; + +describe('add function', () => { + // Fast: This test is very quick to run. + // Independent: This test does not depend on any other tests. + // Repeatable: This test is repeatable, as it will always produce the same result given the same inputs. + // Self-Validating: The test itself will report if it passes or fails. + // Timely: The test is written before the actual function (in a TDD manner). + + it('correctly adds two numbers', () => { + const result = add(1, 2); + expect(result).toBe(3); + }); + + // We can also add more tests to cover more cases + it('correctly adds two negative numbers', () => { + const result = add(-1, -2); + expect(result).toBe(-3); + }); + + it('correctly adds a positive and a negative number', () => { + const result = add(-1, 2); + expect(result).toBe(1); + }); +}); +``` + +** Bad + +```typescript +// add.test.ts + +import { add } from './add'; + +let previousResult = 0; + +describe('add function', () => { + it('correctly adds two numbers', () => { + const result = add(1, 2); + previousResult = result; + expect(result).toBe(3); + }); + + it('correctly adds two other numbers', () => { + const result = add(previousResult, 5); + expect(result).toBe(8); + }); +}); +```