【发布时间】:2019-01-27 08:23:25
【问题描述】:
我有一个设置,我正在编写一个 Angular 应用程序,并使用 JEST 对其进行测试。
一切似乎都在工作,直到我尝试在 Angular 中模仿事件交互。以下测试确实有效:
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();
});
但是,当我尝试使用fixture 的triggerEventHandler('click', null)-方法时,永远不会调用间谍。
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();
});
我确实尝试将它包装在 fakeAsync 中,调用 tick()(和 flush(),就此而言),但它似乎没有任何区别。
主要问题不在于这种情况......因为我可以在本机元素上触发事件,所以更大的问题是我必须测试自定义事件绑定。
有人知道为什么使用原生元素的click-function 有效(我读过它使用DOM 的原生事件冒泡),但使用fixture 的triggerEventHandler 不行吗?更重要的是,我该如何解决这个问题?
提前致谢。
其他信息
我正在使用以下笑话配置(复制自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
}
}
【问题讨论】:
-
我遇到了类似的问题,你有进展吗?
标签: angular typescript jestjs