I'm currently working on an Angular application and testing it with JEST. Everything seems to be running smoothly until I encounter an issue with event interactions in Angular.
The test below works as expected:
it('should delegate click to component', () => {
jest.spyOn(component, 'add');
const button = fixture.debugElement.query(By.css('button > fa-icon[icon="plus"]'));
button.nativeElement.click();
expect(component.add).toHaveBeenCalled();
});
However, when I attempt to use the fixture's
triggerEventHandler('click', null)
method, the spy is not getting invoked.
it('should delegate click to component', () => {
jest.spyOn(component, 'add');
const button = fixture.debugElement.query(By.css('button > fa-icon[icon="plus"]'));
button.triggerEventHandler('click', null);
expect(component.add).toHaveBeenCalled();
});
I've tried wrapping it in fakeAsync
, using tick()
and flush()
, but unfortunately, it doesn't solve the issue.
The main concern here is not just with this specific case. The bigger challenge arises when I need to test custom event bindings.
I'm puzzled as to why using the native element's click
function works (which I've heard leverages the DOM's native event bubbling), but using the fixture's triggerEventHandler
does not. Can anyone shed some light on this issue and suggest a solution?
Thank you in advance.
Additional Information
Here is the jest configuration I am using (copied from package.json
):
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "<rootDir>/src/setup-jest.ts",
"verbose": true,
"testURL": "http://localhost/",
"transform": {
"^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!(@ngrx|ngx-bootstrap))"
],
"globals": {
"ts-jest": {
"tsConfigFile": "src/tsconfig.spec.json",
"useBabelrc": true
},
"__TRANSFORM_HTML__": true
}
}