首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在LWC中测试雷电药丸?

如何在LWC中测试雷电药丸?
EN

Stack Overflow用户
提问于 2020-03-24 06:12:39
回答 1查看 994关注 0票数 1

这是我第一次使用jest测试,我正在尝试测试一种方法,该方法可以从具有访问权限(数组)的组的查询中生成闪电药片。每当一个新组被添加或从数组中移除时,雷电药片就会被更新。

我需要测试以下场景,但我不确定是否正确地创建了测试:

(这些程序在实际代码中已经正常运行)。

Test#1:查询返回的数组应该以闪电药丸的形式显示

Test#2:单击药丸中的X图标应从数组中移除选定的药丸

在这里输入图像描述

对于Test#1,对于多个或单个元素的模拟数组,jest测试失败。我不知道问题出在哪里,但是调试显示这一行是未定义的:

代码语言:javascript
运行
复制
  const detailEls = element.shadowRoot.querySelectorAll('lightning-pill');

我使用的是返回方法GroupController.getSpecificGroups:

具有共享类GroupController {的public

代码语言:javascript
运行
复制
/* Description: Gets the groups where the contact is being shared to
*
*/
@AuraEnabled
public static List<sObject> getSpecificGroups(String recordId){
    List<GroupShare> groupShareList = new List<GroupShare>();
    List<sObject> returnShareList = new List<sObject>();

    try{
        groupShareList = [SELECT Id, UserOrGroupId, UserOrGroup.Name, ContactId, Contact.Name,
                            FROM GroupShare 
                            WHERE ContactId =: recordId];

        if(groupShareList != NULL && !groupShareList.isEmpty()){
            for(GroupShare csBuff : groupShareList){
                returnShareList.add(csBuff);
            }
        }
    }
    catch(queryException qExcp){
    }
    return returnShareList;
}

}

当测试方法成功地将recordId传递到顶点方法调用时,会通过Jest测试,所以我认为方法调用没有问题。

代码语言:javascript
运行
复制
   it('passes the recordId to the Apex method correctly', () => {
        const RECORD_ID = '00AAABBBCCCDDD12345';
        const APEX_PARAMETERS = { recordId: RECORD_ID };

        // Assign mock value for resolved Apex promise
        getSpecificGroups.mockResolvedValue(APEX_GROUPS_SUCCESS);

        // Create initial element
        const element = createElement('c-cmm-specific-group-sharing', {
            is: Cmm_specificGroupSharing
        });
        element.recordId = RECORD_ID;
        document.body.appendChild(element);

        // Select button for executing Apex call
        const buttonEl = element.shadowRoot.querySelector('lightning-button');
        buttonEl.click();

        return flushPromises().then(() => {
            // Validate parameters of mocked Apex call
            expect(getSpecificGroups.mock.calls[0][0]).toEqual(APEX_PARAMETERS);
        });
    });

对于Test#2来说,去药的玩笑试验失败了。使用dispatchEvent不会将药丸从数组中移除:

代码语言:javascript
运行
复制
it('handleRemoveSelectedItem works', () => {
        // Create element
        const element = createElement('c-cmm-specific-group-sharing', {
            is: Cmm_specificGroupSharing
        });
        element.availableGroups = APEX_GROUPS_SUCCESS;
        document.body.appendChild(element);
    
        // Remove a selected item
        const selPills = element.shadowRoot.querySelectorAll('lightning-pill');
        selPills[0].dispatchEvent(new CustomEvent('remove'));
        // Check selection
        expect(element.availableGroups.length).toBe(0);
    });

Jest测试

代码语言:javascript
运行
复制
import { createElement } from 'lwc';
import Cmm_specificGroupSharing from 'c/c-cmm-specific-group-sharing';
import getSpecificGroups from '@salesforce/apex/GroupController.getSpecificGroups';
import delete from "@salesforce/apex/GroupController.delete";

// Mocking  Apex method call
jest.mock(
    '@salesforce/apex/GroupController.getSpecificGroups',
    () => {
        return {
            default: jest.fn()
        };
    },
    { virtual: true }
);

// Sample data for Apex call
const APEX_GROUPS_SUCCESS = [
    {
        "Id": "000001112222DDDD001",
        "UserOrGroupId":  "00AAABBBCCCDDD12345", 
        "Name":  "Asia Pacific"
    }
];

describe('c-cmm-specific-group-sharing', () => {
    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);
        }
        // Prevent data saved on mocks from leaking between tests
        jest.clearAllMocks();
    });

    // Helper function to wait until the microtask queue is empty. This is needed for promise
    // timing when calling imperative Apex.
    function flushPromises() {
        // eslint-disable-next-line no-undef
        return new Promise(resolve => setImmediate(resolve));
    }

   it('passes the recordId to the Apex method correctly', () => {
        const RECORD_ID = '00AAABBBCCCDDD12345';
        const APEX_PARAMETERS = { recordId: RECORD_ID };

        // Assign mock value for resolved Apex promise
        getSpecificGroups.mockResolvedValue(APEX_GROUPS_SUCCESS);

        // Create initial element
        const element = createElement('c-cmm-specific-group-sharing', {
            is: Cmm_specificGroupSharing
        });
        element.recordId = RECORD_ID;
        document.body.appendChild(element);

        // Select button for executing Apex call
        const buttonEl = element.shadowRoot.querySelector('lightning-button');
        buttonEl.click();

        return flushPromises().then(() => {
            // Validate parameters of mocked Apex call
            expect(getSpecificGroups.mock.calls[0][0]).toEqual(APEX_PARAMETERS);
        });
    });

    it('renders one sharing group', () => {
    
        // Assign mock value for resolved Apex promise
        getSpecificGroups.mockResolvedValue(APEX_GROUPS_SUCCESS);

        // Create initial element
        const element = createElement('c-cmm-specific-group-sharing', {
            is: Cmm_specificGroupSharing
        });
        document.body.appendChild(element);

     
        // Select button for executing Apex call
        const buttonEl = element.shadowRoot.querySelector('lightning-button');
        buttonEl.click();

        return flushPromises().then(() => {
      
            const detailEls = element.shadowRoot.querySelectorAll('lightning-pill');
            expect(detailEls.length).toBe(APEX_GROUPS_SUCCESS.length);
            expect(detailEls[0].label).toBe(
                APEX_GROUPS_SUCCESS[0].Name
            );
        });
    });

    it('handleRemoveSelectedItem works', () => {
        // Create element
        const element = createElement('c-cmm-specific-group-sharing', {
            is: Cmm_specificGroupSharing
        });
        element.availableGroups = APEX_GROUPS_SUCCESS;
        document.body.appendChild(element);
    
        // Remove a selected item
        const selPills = element.shadowRoot.querySelectorAll('lightning-pill');
        selPills[0].dispatchEvent(new CustomEvent('remove'));
        // Check selection
        expect(element.availableGroups.length).toBe(0);
    });
});

JS和

代码语言:javascript
运行
复制
import {
    LightningElement
    api
} from 'lwc';

import getSpecificGroups from '@salesforce/apex/GroupController.getSpecificGroups';
import deleteGroup from "@salesforce/apex/GroupController.deleteGroup";
 
export default class Cmm_specificGroupSharing extends LightningElement {

@api availableGroups;
    
@api
get recordId() {
    return this._recordId;
}
set recordId(value) {
    this._recordId = value;
}
connectedCallback() {
      this.getSpecificGroups();
  } 

getSpecificGroups() {
        this.availableGroups =[];
        getSpecificGroups({
                recordId: this._recordId,
            })
            .then(result => {
                result.map(gShare => {
                     let obj = {
                            'Id': gShare.Id,
                            'UserOrGroupId': gShare.UserOrGroupId,
                            'Name': gShare.UserOrGroup.Name
                        };  
                        this.availableGroups.push(obj);
                    return null;
                   
                })
                console.log('result' + JSON.stringify(result));
            })
            .catch((err) => {
            });
    }

handleRemoveSelectedItem(event) {
        const recordId = event.currentTarget.dataset.id;
        this.availableGroups = this. availableGroups.filter(item => item.id !== recordId);

        deleteGroup ({
            recordId: recordId
        })
        .then(() => {
            this.notifyUser('', this.deleteSuccessMsg, 'success');
        })
        .catch((err) => {
            this.error = err;
        });
    }

}
代码语言:javascript
运行
复制
<template>
  <template for:each={availableGroups} for:item="groupShare">
      <lightning-pill
          data-id={groupShare.Id}
          key={groupShare.Id}
          label={groupShare.Name}
          onremove={handleRemoveSelectedItem}>
      </lightning-pill>
  </template> 
</template> 

我很感谢你的帮助。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-04-03 14:48:28

拜托,你能试试这样吗?:

代码语言:javascript
运行
复制
it('handleRemoveSelectedItem works', () => {
    // Create element
    const element = createElement('c-cmm-specific-group-sharing', {
        is: Cmm_specificGroupSharing
    });
    element.availableGroups = APEX_GROUPS_SUCCESS;
    document.body.appendChild(element);

    return Promise.resolve()
    .then(() => {
         // Remove a selected item
        let selPills = element.shadowRoot.querySelectorAll('lightning-pill');
        selPills[0].dispatchEvent(new CustomEvent('remove'));
    }) // Move foward
    .then(() => {
        selPills = element.shadowRoot.querySelectorAll('lightning-pill');
        expect(selPills.length).toBe(0);
    });
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60825789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档