Unit Testing

Unit-testing is not optional if you care about quality and your personal health.

Unit testing improves teams efficiency, applications quality and human lifespan.

Without automated tests:

  • every change is a challenge,

  • updating dependencies is too risky,

  • refactoring is inacceptable,

  • deployment is chaos,

  • ...

Modularity is unit testing's best friend.

JavaScript Unit-Test Frameworks

Jasmine

https://jasmine.github.io/

Mocha

https://mochajs.org/

Jest

https://jestjs.io/

Jasmine

Example

describe('priceScrapper', () => {

    let priceScrapper;
    
    beforeEach(() => priceScrapper = new PriceScrapper());

    it('should scrap prices without currency', () => {

        expect(priceScrapper.scrap('10.01')).toEqual({
            coefficient: 1001,
            currency: null,
            exponent: -2
        });

    });

    it('should scrap prices with currency', () => {

        expect(priceScrapper.scrap('$10.01')).toEqual({
            coefficient: 1001,
            currency: 'USD',
            exponent: -2
        });

    });

});

Spies

Jasmine spies are mocks.

describe('SearchEngine', () => {

    it('should pass locale to third party api', () => {

        /* Spying on `thirdPartySearchApi.search` and faking result. */
        spyOn(thirdPartySearchApi, 'search').and.returnValue([
            {
                title: 'Wishtack - Making Your Wishes Come True',
                url: 'https://www.wishtack.com'
            }
        ]);

        /* Trigger search. */
        searchEngine.search({keywords: 'Wishtack'});

        /* Check spy's call count. */
        expect(thirdPartySearchApi.search.callCount).toBe(1);

        /* Check spy's call args. */
        expect(thirdPartySearchApi.search).toHaveBeenCalledWith({
            country: 'US',
            keywords: 'Wishtack',
            language: 'en'
        });

    });

});

Fetch Mock

If you are using fetch for HTTP requests, you can use fetch-mock to mock these http requests.

http://www.wheresrhys.co.uk/fetch-mock/quickstart

Last updated