Тестовый блок Jest для прослушивания click
Событие, генерируемое дочерним элементом, вызывает ошибку
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
// .spec.ts code
import { newSpecPage } from '@stencil/core/testing';
import { MyComponent } from './my-component';
import { MyEmbeddedComponent } from './my-embedded-component';
describe('click event', () => {
let page;
beforeEach(async () => {
page = await newSpecPage({
components: [MyComponent, MyEmbeddedComponent],
html: '<my-component color="green"></my-component>'
});
});
it('should emit click event', async () => {
let callbackFn = jest.fn();
page.doc.addEventListener('clickCompleted', callbackFn);
const button = page.root.shadowRoot.querySelector('button');
await button.dispatchEvent(new Event('clickCompleted'));
await page.waitForChanges();
expect(callbackFn).toHaveBeenCalled();
});
})
// my-embedded-component.ts
import { Component, Prop, h, Event, EventEmitter } from '@stencil/core';
@Component({
tag: 'my-embedded-component'
})
export class MyEmbeddedComponent {
@Prop() color: string;
@Event() clickCompleted: EventEmitter;
handleClickCompleted() {
console.log('Emitting clickCompleted event');
this.clickCompleted.emit(4);
}
render() {
return (
<button onClick={this.handleClickCompleted.bind(this)}>I'm a child</button>
);
}
}
// my-component.tsx
import { Component, h, Listen } from '@stencil/core';
@Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: true
})
export class MyComponent {
@Listen('clickCompleted')
listenClickCompleted(e: CustomEvent) {
console.log('Listening listenClickCompleted ', e.detail);
}
render() {
return <div class='hello'><my-embedded-component color="green"></my-embedded-component></div>;
}
}