How can I make sure, in an unit test, that I have the correct data in a lightning-map component?

If I have a property called markers in my component, which is exposed using the @api notation. How can I make sure that it contains the correct values after the component goes through the jest unit test?

I know that using the following throws an error, because the property is being passed as undefined:

expect(comp.mapMarkers).toHaveLength(2)

Outputting:

expect(received)[.not].toHaveLength(length)

Expected value to have a 'length' property that is a number. Received:
  undefined

However, I have the lightning-map component around a template tag in which the condition to be rendered is that the mapMarkers property mustn’t be null or empty:

<template if:true={mapMarkers}>
    <lightning-map
        map-markers={mapMarkers}
        markers-title={markersTitle}
        zoom-level={zoomLevel}
    ></lightning-map>
</template>

And the following assertion passes:

expect(comp.shadowRoot.querySelector('lightning-map')).not.toBeNull()

Which means, in my understanding, that the map component should be rendered on the screen.

Answer

Turns out that it is possible to get the component’s attributes in a simple way, just accessing them directly, like:

expect(comp.mapMarkers).toHaveLength(2)

The catch here is that you have to “return a promise in the unit test, to wait for any asynchronous DOM updates. Jest will automatically wait for the Promise chain to complete before ending the test and fail the test if the promise rejects.

So the last lines of the test method look like this:

it('Should render the map with two markers.', () => {

    // ... mocking, instancing, etc


    // asserts the child component is rendered in our component
    expect(comp.shadowRoot.querySelector('lightning-map')).not.toBeNull()

    // asserts the property is properly populated with the information
    // that comes from the database (which was mocked in the beginning
    // of the test)
    return Promise.resolve(() => {
        expect(comp.mapMarkers).toHaveLength(2)
    })
})

This solution was found on a snippet on the blog post “Unit Test Lightning Web Components with Jest”, under the section “Salesforce specifics”.

https://developer.salesforce.com/blogs/2019/03/unit-test-lightning-web-components-with-jest.html

Attribution
Source : Link , Question Author : Renato Oliveira , Answer Author : Renato Oliveira

Leave a Comment