0

I'm trying to make unit test with Jest for my lightning web component.

I'm trying to check if the data binded in my html are rendering correctly.

It seems like when i'm running the test, it doesn't give enough time for the data to be binded and keep returning 0 for some reason i ignore.

If someone know why this behaviour is happening would be very helpfull since i'm locked at this step.

Here is my syntheseComponent.js :

import { LightningElement, api, wire, track } from 'lwc';
import getSyntheseData from '@salesforce/apex/SyntheseController.getSyntheseData';

export default class SyntheseComponent extends LightningElement {
    @api recordId;
    @track syntheseData;//NOTE: added own property now

    get countContact() { 
      return this.syntheseData ? this.syntheseData.countContact : 0;
    }

    @wire(getSyntheseData, { accId: '$recordId' })
    wiredSyntheseData({error, data}) {
      if(error) {
        // eslint-disable-next-line no-console
        console.error(error);
      } else if(data) {
        this.syntheseData = data;
      }
    }
  }

The test i'm trying in my syntheseComponent.test.js :

import { createElement } from 'lwc';
import { registerTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
import SyntheseComponent from 'c/syntheseComponent';
import getSyntheseData from '@salesforce/apex/SyntheseController.getSyntheseData';

// Import mock data to send through the wire adapter.
const mockGetSyntheseData = require('./data/getSyntheseData.json');

// Register a test wire adapter to control @wire(getRecord)
const getRecordWireAdapterSyntheseData = registerTestWireAdapter(getSyntheseData);

describe('c-synthese-component', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
        jest.clearAllMocks();
    });

    it('It renders my component', () => {
        // Create element
        const element = createElement('c-synthese-component', {
            is: SyntheseComponent
        });
        document.body.appendChild(element);

        return Promise.resolve().then(() => {
            const content = document.body.querySelector('c-synthese-component');
            expect(content).not.toBeNull();
        });
    });

    it('It renders my data', () => {
        // Create element
        const element = createElement('c-synthese-component', {
            is: SyntheseComponent
        });
        document.body.appendChild(element);
        getRecordWireAdapterSyntheseData.emit(mockGetSyntheseData);

        return Promise.resolve().then(() => {
        const dd = element.shadowRoot.querySelector('dd[data-id=child-id]');
        const countField = mockGetSyntheseData.countContact;
        expect(dd.textContent).toBe(`Nb Contacts: ${countField}`);
        }); 
    });
});

The getSyntheseData.json i'm using :

{
  "amountOpportunity": 100,
  "amountOpportunityB2B": 50,
  "amountOpportunityB2BAbo": 30,
  "amountOpportunityB2BPlacesSeches": 20,
  "amountOpportunityEvent": 30,
  "amountOpportunityLagardere": 20,
  "countContact": 2,
  "countOpenactivities": 3,
  "countOpportunity": 5,
  "countOpportunityB2B": 3,
  "countOpportunityB2BAbo": 1,
  "countOpportunityB2BPlacesSeches": 2,
  "countOpportunityEvent": 1,
  "countOpportunityLagardere": 1,
  "lastCreatedOpportunityB2BFormated": "15/01/2020",
  "lastCreatedOpportunityEventFormated": "05/11/2019",
  "lastCreatedOpportunityFormated": "15/01/2020",
  "lastCreatedOpportunityLagardereFormated": "14/01/2020"
}

And a part of my syntheseComponent.html :

<lightning-tab label="Général">
        <div class="slds-m-around_medium" data-id="parent-id">
          <dl class="slds-list_horizontal slds-wrap">
            <dt class="slds-dl_horizontal__label slds-text-color_weak slds-truncate" data-id="contact-id" title="Contacts">Nb Contacts:</dt>
            <dd class="slds-dl_horizontal__detail slds-text-color_weak slds-truncate numberStyle" data-id="child-id" title="Description for first label">{countContact}</dd>
            <dt class="slds-dl_horizontal__label slds-text-color_weak slds-truncate" title="Opportunités">Nb Opportunités:</dt>
            <dd class="slds-dl_horizontal__detail slds-text-color_weak slds-truncate numberStyle" title="Description for second label">{countOpportunity}</dd>
            <dt class="slds-dl_horizontal__label slds-text-color_weak slds-truncate" title="Montant">Montant Opportunités:</dt>
            <dd class="slds-dl_horizontal__detail slds-text-color_weak slds-truncate numberStyle" title="Description for second label">{amountOpportunity}€</dd>
            <dt class="slds-dl_horizontal__label slds-text-color_weak slds-truncate" title="Open Activities">Open Activities:</dt>
            <dd class="slds-dl_horizontal__detail slds-text-color_weak slds-truncate numberStyle" title="Description for second label">{countOpenactivities}</dd>
            <dt class="slds-dl_horizontal__label slds-text-color_weak slds-truncate" title="Date dernière opp">Dernière Opportunité:</dt>
            <dd class="slds-dl_horizontal__detail slds-text-color_weak slds-truncate numberStyle" title="Description for second label">{lastCreatedOpportunityFormated}</dd>
          </dl>
        </div>
      </lightning-tab>

And the error i have while running my test :

error

  • As a general rule, it would help if you reduce the amount of code that you share to the bare minimum of what's needed for your question. – POZ Feb 12 at 15:40
  • For example we don't need to see all of the getters or the other tests but we do need to see your HTML and the sample JSON file you're using. – POZ Feb 12 at 15:41
  • Oh ok sorry i will edit my post with the JSON file i'm using and the HTML. Should i let at least one getter? Because it seems like the issue is coming from here. – Adrien Merignac Feb 12 at 15:52
  • Yes leave at least one getter since your code uses that for the test. – POZ Feb 12 at 15:55
  • I edited with leaving just one getter, adding my JSON file and a part of my HTML component. – Adrien Merignac Feb 12 at 15:57
0

I see several issues with you test code:

  1. Your div[data-id=parent-id] query selector in your test returns the parent div and not the dd element you're looking for. You need to change the selector and or the markup to select the right node.

  2. You're not clearing mocks between tests. Add jest.clearAllMocks(); to the afterEach function.

| improve this answer | |
  • Edited my code and the Screenshoot of the error. Still receiving 0 even with adding jest.clearAllMocks(); and querying the good dd. – Adrien Merignac Feb 12 at 16:42
  • Your assert needs to be expect(dd.textContent).toBe(countField); (remove the string from the expected value) and you need to update your markup to link to the right object {syntheseData.countContact} (it's missing the syntheseData bit. – POZ Feb 12 at 16:47
  • stupid question but when you say update your markup it's in my syntheseComponent.html? – Adrien Merignac Feb 12 at 18:28
  • Yes. Your component is "broken" and the test is correctly reporting that issue. – POZ Feb 12 at 19:41
  • Hi, i changed my syntheseComponent.html to add the markup as you said {syntheseData.countContact} Then it gives me the error [Cannot read property 'countContact' of undefined]... – Adrien Merignac Feb 17 at 8:19

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.