1

I have a Lightning Web Component with the following HTML:

<template>
     <h1>Current price of a bitcoin in Euro</h1>
     <lightning-formatted-number currency-code="EUR"
                            format-style="currency"
                            value={euroPrice}
     ></lightning-formatted-number>
</template>

and the following JavaScript:

    import {LightningElement, api, track} from 'lwc';

const bitcoinPriceProvider = 'https://api.coinbase.com/v2/prices/spot?currency=EUR';
export default class BitcoinEuroPrice extends LightningElement {
    @api
    refreshRateInSeconds;

    @track
    euroPrice;

    connectedCallback() {
        this.fetchPrice();
        setInterval(this.fetchPrice, this.refreshRateInSeconds * 1000);
    }

    fetchPrice() {
        fetch(bitcoinPriceProvider)
            .then(response => response.json())
            .then(json => {
                this.euroPrice = json.data.amount;
            });
    }
}

I am trying to create a Jest test for it, but the test fails when I try to mock out the fetch operation:

This is the test:

import {createElement} from 'lwc';

import BitcoinEuroPrice from 'c/bitcoinEuroPrice';

describe('c-bitcoinEuroPrice', () => { afterEach(() => { while (document.body.firstChild) { document.body.removeChild(document.body.firstChild); } });

it('fetches price', () => {
    // Arrange
    const testAmount = '8448.947391885';
    const mockApiResponse = {
        'data': {
            'base': 'BTC',
            'currency': 'EUR',
            'amount': testAmount
        }
    };
    fetch = global.fetch = mockFetch(mockApiResponse);

    // Act
    const priceUnderTest = createElement('c-bitcoinEuroPrice', {
        is: BitcoinEuroPrice
    });
    console.log('######## priceUnderTest', priceUnderTest);

    // Assert
    expect(global.fetch).toHaveBeenCalledTimes(1);
    expect(global.fetch).toHaveBeenCalledWith('https://api.coinbase.com/v2/prices/spot?currency=EUR');
    expect(priceUnderTest.euroPrice).toEqual(testAmount);
});

function mockFetch(mockApiResponse) {
    return jest
        .fn()
        .mockImplementationOnce(() =>
            Promise.resolve({
                ok: true,
                json: () => Promise.resolve(mockApiResponse),
                jsonResponse: mockApiResponse
            })
        );
}

});

and this is the error:

FAIL force-app/main/default/lwc/bitcoinEuroPrice/tests/bitcoinEuroPriceTest.js c-bitcoinEuroPrice × fetches price (32ms)

● c-bitcoinEuroPrice › fetches price

expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0

  28 | 
  29 |         // Assert
> 30 |         expect(global.fetch).toHaveBeenCalledTimes(1);
     |         ^
  31 |         expect(global.fetch).toHaveBeenCalledWith('https://api.coinbase.com/v2/prices/spot?currency=EUR');
  32 |         expect(priceUnderTest.euroPrice).toEqual(testAmount);
  33 |     });
    ^

Any idea how I can mock out or spy onfetch successfully?

Thanks.

2

Seems the problem was that I needed to connect the element to execute the connectedCallback.

(Duh!!!)

e.g.:

        // Act
        const priceUnderTest = createElement('c-bitcoinEuroPrice', {
            is: BitcoinEuroPrice
        });
        document.body.appendChild(priceUnderTest);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.