0
import { createElement } from 'lwc';
import ConversationWebComponent from 'c/conversationWebComponent';
import {setImmediate} from 'timers';
import getConversationData from '@salesforce/apex/OmniCentralClass.getConversationData';
import getMatterData from '@salesforce/apex/OmniCentralClass.getMatterData';

const partyData = require('./mockData/partyData.json');
const latestMessageData = require('./mockData/latestMessageData.json')
const matterData = require('./mockData/matterData.json')
const conversationData = require('./mockData/conversationData.json');

// Mocking Apex calls
jest.mock('@salesforce/apex/OmniCentralClass.getConversationData', () => {
    const {createApexTestWireAdapter} = require("@salesforce/sfdx-lwc-jest")
    return {
        default: createApexTestWireAdapter(jest.fn())
    }
}, {virtual: true})

jest.mock('@salesforce/apex/OmniCentralClass.getMatterData', () => {
    const {createApexTestWireAdapter} = require("@salesforce/sfdx-lwc-jest")
    return {
        default: createApexTestWireAdapter(jest.fn())
    }
}, {virtual: true})

describe('Testing LWC', () => {
    beforeEach(() => {
        const element = createElement('c-conversation-web-component', {
            is: ConversationWebComponent
        })
        document.body.appendChild(element)
    });
    afterEach(() => {
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    test("displays product name field", () => {
        const element = createElement("c-conversation-web-component", {
            is: ConversationWebComponent
        });
        document.body.appendChild(element);
        console.log("element: ", element);
        // Emit mock record into the wired field
        getConversationData.emit(conversationData)
        getMatterData.emit(matterData)
      
        // Resolve a promise to wait for a rerender of the new content.
        return Promise.resolve().then(() => {
          const content = element.shadowRoot.querySelector(".messageBody");
          console.log('content: ', content);
          const nameField = conversationData[0].banjaxed_cm__Latest_Message__r.banjaxed_cm__Message_Body__c;
          console.log(nameField);
        //   expect(content.textContent).toBe(`Name:${nameField}`);
        });
      });
});

I have written this jest code. My content variable is coming null even though I have defined the class messageBody in my lwc html component.

My html code is:

    <template>
    <div onchange={showMessageOrTable} class="main-container">
        <template if:true={showMessage}>
            <div class="table-container">
                <table class="slds-table slds-table_bordered slds-table_cell-buffer slds-table_col-bordered" role="grid">
                    <thead>
                        <tr class="slds-line-height_reset">
                            <th scope="col">
                                <div class="slds-truncate" title="Responsible User(s)">Responsible User(s)</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Party Name">Party Name</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Message Body">Message Body</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Created Date">Message Created Date</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Open Matters">Open Matters (Display Name and Status)</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Responsible User">Responsible User</div>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <template for:each={pageFlattenedData} if:true={pageFlattenedData.length} for:item="record" for:index="index">
                            <tr key={record.id} class="record-row">
                                <td rowspan={record.rowSpan} class="slds-text-align_left">
                                    <div class="slds-truncate">{record.uniqueUsersList}</div>
                                </td>
                                <td rowspan={record.rowSpan} class="slds-text-align_left ">
                                    <div class="slds-truncate">
                                        <a href={record.partyId} class="party-name" target="_blank">{record.partyName}</a>
                                    </div>
                                </td>
                                <td rowspan={record.rowSpan} class="slds-text-align_left messageBody">
                                    <div class="slds-truncate ">{record.messageBody}</div>
                                </td>
                                <td rowspan={record.rowSpan} class="slds-text-align_left">
                                    <div class="slds-truncate">{record.createdDate}</div>
                                </td>
                            </tr>
                            <template for:each={record.openMatters} for:item="matter" for:index="matterIndex">
                                <tr key={matter.id}>
                                    <td rowspan={matter.userRowSpan} class="slds-text-align_left">
                                        <div class="slds-truncate">
                                            <a href={matter.matterLink} target="_blank">{matter.matterName}</a>
                                        </div>
                                    </td>
                                </tr>
                                <template for:each={matter.responsibleUsers} for:item="user">
                                    <tr key={matter.id}>
                                        <td class="slds-text-align_left">{user.name}</td>
                                    </tr>
                                </template>
                            </template>
                        </template>
                    </tbody>
                </table>
            </div>
            <footer slot="footer" style="text-align: center" class="pagination-footer">
                <ul class="slds-pagination">
                    <li class="slds-button slds-button_icon page-item" key={previousKey} onclick={previousPage}>
                        <a class="slds-button__icon" href="javascript:void(0);" aria-label="Previous">
                            <lightning-icon icon-name="utility:left" size="x-small"></lightning-icon>
                        </a>
                    </li>
                    <template for:each={pages} for:item="page">
                        <li class="slds-button slds-button_icon page-item" key={page.key} onclick={gotoPage}>
                            <a class="slds-button__icon" href="javascript:void(0);">{page.number}</a>
                        </li>
                    </template>
                    <li class="slds-button slds-button_icon page-item" key={nextKey} onclick={nextPage}>
                        <a class="slds-button__icon" href="javascript:void(0);" aria-label="Next">
                            <lightning-icon icon-name="utility:right" size="x-small"></lightning-icon>
                        </a>
                    </li>
                </ul>
            </footer>
        </template>
        <template if:false={showMessage}>
            <!-- <div class="messageClass">
                <span>No Unresolved Conversations Found</span>
            </div> -->
            <lightning-card title="No Unresolved Conversations Found"></lightning-card>
        </template>
    </div>
</template>

and the code in my js:

import { LightningElement, wire, track } from 'lwc';
import getConversationData from '@salesforce/apex/OmniCentralClass.getConversationData';
import getMatterData from '@salesforce/apex/OmniCentralClass.getMatterData';

const PAGE_SIZE = 10; // Number of records per page

export default class ConversationWebComponent extends LightningElement {
    allConversationData = [];
    allMatterData = [];
    flattenedData = [];
    pageFlattenedData = [];
    showMessage = false;

    @track currentPage = 1;
    @track totalRecords = 0;
    @track pages = [];
    @track displayedData = [];

    formatDate(dateString) {
        // Parse the date string into a Date object
        const date = new Date(dateString);

        // Format the date using toLocaleDateString() method
        // Adjust options based on your desired format
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }

    conFunction(data) {
        this.allConversationData = data.map(record => ({
            id: record.Id,
            messageBody: record.banjaxed_cm__Latest_Message__r.banjaxed_cm__Message_Body__c,
            partyId: record.banjaxed_cm__Party__c ? `/${record.banjaxed_cm__Party__c}` : '',
            partyName: record.banjaxed_cm__Party__c ? record.banjaxed_cm__Party__r.Name : '',
            createdDate: this.formatDate(record.banjaxed_cm__Latest_Message__r.CreatedDate),
            testPartyId: record.banjaxed_cm__Party__c ? record.banjaxed_cm__Party__c : ''
        }));
    }

    @wire(getConversationData)
    wiredConversationData({ error, data }) {
        if (data) {
            this.conFunction(data)
        } else if (error) {
            console.error(error);
        }
    }

    matterData(data) {
        let matterDict = {};

        matterDict = data.reduce((acc, matter) => {
            if (!acc[matter.Id]) {
                acc[matter.Id] = [];
            }
            if(matter.Responsible_for_SMS__c){
                acc[matter.Id].push({
                    name: matter.Responsible_for_SMS__c
                })
            }
            return acc;
        }, {});

        this.allConversationData.forEach(record => {
            let relatedMatters = data.filter(matter => matter.litify_pm__Client__c === record.testPartyId);
            if (relatedMatters.length > 0) {
                let responsibleUsersList = [];
                relatedMatters.forEach(matter => {
                    if(matter.Responsible_for_SMS__c) {
                        responsibleUsersList.push(matter.Responsible_for_SMS__c)
                    }
                })
                console.log("user list: ", responsibleUsersList);
                // Remove duplicate values
                const uniqueUsersList = [...new Set(responsibleUsersList)];

                console.log(uniqueUsersList);
                let openMatters = relatedMatters.map(matter => ({
                    id: matter.Id,
                    matterName: `${matter.litify_pm__Display_Name__c} (${matter.litify_pm__Status__c})`,
                    matterLink: `/${matter.Id}`,
                    responsibleUsers: matterDict[matter.Id],
                    userRowSpan: matterDict[matter.Id].length + 1
                }))
                const totalRelatedMatters = relatedMatters.length;
                const totalResponsibleUsers = relatedMatters.reduce((acc, matter) => acc + matterDict[matter.Id].length, 0);
                const responsibleUserRowSpan = totalRelatedMatters + totalResponsibleUsers;
                this.flattenedData.push({
                    ...record,
                    uniqueUsersList,
                    openMatters,
                    rowSpan: responsibleUserRowSpan + 1
                })
            }
        });
        this.totalRecords = this.flattenedData.length;

        // Calculate total number of pages
        const totalPages = Math.ceil(this.totalRecords / PAGE_SIZE);
        this.pages = [];
        for (let i = 1; i <= totalPages; i++) {
            this.pages.push({ number: i, key: i });
        }
        this.setData()
        console.log("Modified flattenedData: ", this.pageFlattenedData);
    }

    @wire(getMatterData)
    wiredMatterData({ error, data }) {
        if (data) {
            this.matterData(data);
        } else if (error) {
            console.error(error);
        }
    }

    setData() {
        // Slice and display the current page's records
        const startIndex = (this.currentPage - 1) * PAGE_SIZE;
        const endIndex = startIndex + PAGE_SIZE;
        this.pageFlattenedData = this.flattenedData.slice(startIndex, endIndex);
    }

    previousPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            this.fetchData();
        }
    }
    
    nextPage() {
        if (this.currentPage < this.pages.length) {
            this.currentPage++;
            this.fetchData();
        }
    }
    
    gotoPage(event) {
        const pageNumber = event.target.innerText;
        this.currentPage = parseInt(pageNumber);
        this.fetchData();
    }

    fetchData() {  
        this.pageFlattenedData = []
        setTimeout(() =>  this.setData(), 0);
    }

    showMessageOrTable() {
        console.log("munib was here");
        if(this.pageFlattenedData && this.pageFlattenedData.lenght > 0)
            this.showMessage = true
        else this.showMessage = false
    }
}

can anyone tell me what could be the problem. my mock data is also being created.

0

1 Answer 1

1

if(this.pageFlattenedData && this.pageFlattenedData.lenght > 0)

This should be length. this.showMessage never gets true.

If I were you, I'd move the methods below @wire to a separate Javascript module. A separate module can be tested much more easily, because unit tests can directly test individual methods. E.g. above problem would almost for sure have come to light writing a unit test for showMessageOrTable().

You must log in to answer this question.

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