3

I'm populating the data table in the jest test successfully but when I try to select any row it comes up null which leads to this error TypeError: dataTableRow.click is not a function

this is from my test

.then(() => {
        const dataTableRow = element.getElementsByClassName("slds-checkbox");
        expect(dataTableRow).toBeTruthy();
        const test = element.shadowRoot.querySelector("lightning-primitive-cell-checkbox");
        dataTableRow.click();
      })

Also jest has this error from the lwc js file when testing if I comment out the dataTableRow.click(); TypeError: Cannot read property 'getSelectedRows' of null which is caused in my handleSubmit function

handleSubmit(event) {
    event.preventDefault(); // stop the form from submitting
    const fields = event.detail.fields;
    if (this.isSubmitable(fields)) {
      this.selectedAccounts = this.template.querySelector("lightning-datatable").getSelectedRows();
       
7
  • Why are you testing a standard component?
    – Phil W
    Sep 2, 2020 at 22:03
  • because it's used in a lwc that needs code coverage which requires setting values in a table and selecting and verify data that is selected.
    – James
    Sep 2, 2020 at 22:07
  • 1
    Should you not be mocking out this component? Basically you want to test your code, not Salesforce’s code...
    – Phil W
    Sep 2, 2020 at 22:09
  • That could work. Could you provide and example how to mock this.template.querySelector("lightning-datatable").getSelectedRows(); this is the line that is used in the code to get the data from the the table that has been selected
    – James
    Sep 2, 2020 at 22:22
  • 1
    Great. Can I suggest you turn your comment into an answer so future searches will find an answered question, and I can update it too :)
    – Phil W
    Sep 3, 2020 at 6:02

1 Answer 1

1

The answer of this question can be found here: How to mock custom LWC components in JEST

So you just need to mock the method from the datatable:

    .then(() => {
        const dataTableRow = element.getElementsByClassName("slds-checkbox");
        expect(dataTableRow).toBeTruthy();
        dataTableRow.getSelectedRows = jest.fn().mockImplementation( () => { return ['yourRecordHere'] });
        const test = element.shadowRoot.querySelector("lightning-primitive-cell-checkbox");
        dataTableRow.click();
      })

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .