这是我第一次使用jest测试,我正在尝试测试一种方法,该方法可以从具有访问权限(数组)的组的查询中生成闪电药片。每当一个新组被添加或从数组中移除时,雷电药片就会被更新。
我需要测试以下场景,但我不确定是否正确地创建了测试:
(这些程序在实际代码中已经正常运行)。
Test#1:查询返回的数组应该以闪电药丸的形式显示
Test#2:单击药丸中的X图标应从数组中移除选定的药丸
对于Test#1,对于多个或单个元素的模拟数组,jest测试失败。我不知道问题出在哪里,但是调试显示这一行是未定义的:
const detailEls = element.shadowRoot.querySelectorAll('lightning-pill');
我使用的是返回方法GroupController.getSpecificGroups:
具有共享类GroupController {的public
/* 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测试,所以我认为方法调用没有问题。
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不会将药丸从数组中移除:
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测试
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和
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;
});
}
}
<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>
我很感谢你的帮助。谢谢!
发布于 2020-04-03 14:48:28
拜托,你能试试这样吗?:
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);
});
});
https://stackoverflow.com/questions/60825789
复制相似问题