Hello everyone πββοΈ, in this post I'm going to explain how to do a simple unit test with typescript and jest.
First of all, I'll make a function that solves the problem known as fizzbuzz and then I'll unit test the solution.
Fizzbuzz problem: Write a code that prints numbers from 1 to 100 to the console. If the number is a multiple of 3, print the word βfizzβ. If the number is a multiple of 5, print the word "buzz". If the number is a multiple of 3 and 5, print the word "fizzbuzz".
To solve the problem, let's create a main class and add a function called fizzbuzz that takes a parameter and evaluates it based on the given conditions.
// 01-basic.ts
export class Main {
fizzbuzz(num: number): string {
if ( num % 3 === 0 && num % 5 === 0 ) {
return 'fizz buzz';
}
if ( num % 3 === 0 ) {
return 'fizz';
}
if ( num % 5 === 0 ) {
return 'buzz';
}
return `${num}`;
}
}
Now, let's create a spec file and write the following code:
// 01-basic.spec.ts
import { Main } from "./01-basic";
describe('@MainTest', () => {
let component: Main;
beforeEach(() => {
component = new Main();
})
})
π¨βπ« Explanation: We just create the container for unit tests. Describe function takes two parameters, the first ('@MainTest') is its name and you can name it whatever you want. The second is a jest function and inside it we create a variable of the type of our class and then initialize it in a structure called beforeEach. As its name says, inside it we put all the variables or functions that need to be initialized or executing before executing the unit test.
Before writing our first use case for testing, we need to read about a well-known pattern for writing tests: PATTERN ARRANGE-ACT-ASSERT
Following the pattern, let's write βοΈ the solution to our first use case:
Test #1: call function with a number multiple of 3 and 5 and return 'fizzbuzz'
- Arrange => create a constant with the number to evaluate.
- Act => evaluate the number in the fizzbuzz function.
- Assert => compare the output of the fizzbuzz function and the expected result.
// Pattern Arrange-Act-Assert
it('should return fizz buzz if number es mod 3 and 5', () => {
// arrange
const numberToEvaluate = 30;
// act
const result = component.fizzbuzz(numberToEvaluate);
// assert
expect(result).toEqual('fizz buzz');
})
After running jest test command, we get the following output π:
Now, you need to create all the tests necessary to cover π― percent of the class.
I hope this post has helped you π. I'll make other posts with other examples that I know might be helpful π€.
Solution repository: https://github.com/JuanSW18/unit-test-examples/blob/master/01-basic.spec.ts
Top comments (0)