Skip to content

04 describe it

ranhs edited this page Mar 11, 2021 · 4 revisions

Demo.ts

export function add(a: number, b: number): number {
    return a + b
}

The code above is that code that is in the Demo.ts file.
It includes a single function that gets 2 numbers and returns their sum. We want to write a test code for this function

Demo.test.ts

For testing the code in Demo.ts we will create a file named Demo.test.ts that lay beside the original Demo.ts
In this file we will define a class that will hold our test code:

class TestDemo {
}

Next we need to mark the class as a test class. We will do that using the decorator describe (same name as in mocha), and we will also name what we are testing in this class as 'demo', since we are testing the Demo.ts file

import { describe } from 'soda-test'

@describe('demo')
class TestDemo {
}

We will import the decorator from the 'soda-test' libraray (as will do for any other decorator, method or type)
Inside the test class, we will define a method for a basic testing of the add method, also known as test-step.

import { describe, TR } from 'soda-test'

@describe('demo')
class TestDemo {

    addBasic(): TR {
    }

}

Note: TR (Test Result) is the retun value of the test-step method. not relevant at this point.

Next we need to mark this method as a test-step, using the it decorator (same name as in mocha) and provide it, the text that describe what it is testing

import { describe, it, TR } from 'soda-test'

@describe('demo')
class TestDemo {

    @it('should add two numbers')
    addBasic(): TR {
    }

}

Note that the it can be used without an argument, in this case it will use the name of the method as the test-step.
In the test-step-method we will call the add method we are testing, pass it 1 and 2, and validate that the return value is 3.
The validation is done using the expect method

import { expect, describe, it, TR } from 'soda-test'
import { add } from './demo'

@describe('demo')
class TestDemo {

    @it('should add two numbers')
    addBasic(): TR {
        expect(add(1,2)).to.equal(3)
    }

}

Note that expect method is imported from 'soda-test', but it is the same expect method of the chai libraray. See chai documenation for all you can do with the expect method.