> For the complete documentation index, see [llms.txt](https://web-dev-guide.wishtack.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://web-dev-guide.wishtack.io/testing/unit-testing.md).

# Unit Testing

{% hint style="warning" %}
Unit-testing is **not optional** if you care about quality and your personal health.
{% endhint %}

{% hint style="success" %}
Unit testing improves teams **efficiency**, applications **quality** and **human lifespan**.
{% endhint %}

**Without automated tests:**

* every change is a challenge,&#x20;
* updating dependencies is too risky,
* refactoring is inacceptable,
* deployment is chaos,
* ...

{% hint style="success" %}
Modularity is unit testing's best friend.
{% endhint %}

## JavaScript Unit-Test Frameworks

### Jasmine

<https://jasmine.github.io/>

{% embed url="<https://jasmine.github.io/>" %}

### Mocha

<https://mochajs.org/>

{% embed url="<https://mochajs.org/>" %}

### Jest

<https://jestjs.io/>

{% embed url="<https://jestjs.io/>" %}

## Jasmine

### Example

```javascript
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.

```javascript
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>

{% embed url="<http://www.wheresrhys.co.uk/fetch-mock/quickstart>" %}
