I am failing to understand the error source in my first attempt at 'jesting'.
import { createElement } from 'lwc';
import Lwcsearchcomponent from 'c/lwcsearchcomponent'
describe('lwcsearchcomponent test suite', ()=>{
afterEach(()=>{
while (document.body.firstChild){
document.body.removeChild(document.body.firstChild);}
});
async function flushPromises() {
return Promise.resolve();
}
it('Input dispatches correctly', async()=>{
const element = createElement('c-lwcsearchcomponent', {
is:Lwcsearchcomponent
})
let searchEvent = new CustomEvent('search',{
detail : { value : 'An' }
});
this.dispatchEvent(searchEvent);
document.body.appendChild(element);
const handler = jest.fn()
element.addEventListener(searchEvent, handler);
const inputElement = element.shadowRoot.querySelector('lightning-input['string-input']')
inputElement.dispatchEvent.searchEvent()
await flushPromises();
expect(handler).toHaveBeenCalled();
})
The LWC (child) is:
<template>
<lightning-input
type="search"
value={searchKeyword}
onchange={handleChange}
label={searchLabel}
placeholder={placeHolder}
class="string-input"
is-loading
> </lightning-input>
</template>
and
import { LightningElement, api } from 'lwc';
export default class Lwcsearchcomponent extends LightningElement {
@api searchLabel;
@api placeholder;
handleChange(event) {
var keyword = event.target.value;
if ( keyword && keyword.length >= 2 ) {
let searchEvent = new CustomEvent('search',{detail : { value : keyword }});
this.dispatchEvent(searchEvent);
}
}
}
Error is:
TypeError: Cannot read properties of null (reading 'dispatchEvent')
It dispatches the input value to the parent correctly, but I am trying to conquer testing.
I would be most greatful for guidance.
Best Answer
this.dispatchEvent(searchEvent);
near the top of the unit test won't work. You need to dispatch the event from an element.