angular - Angular 单元测试:访问模板变量
问题描述
我在组件模板中有这段代码,它打开了一个 ngx-bootstrap 模式:
<button type="button"
class="btn btn-primary"
(click)="onOpenSharesModal(modal)">Click me!</button>
<ng-template #modal>
<app-modal (closed)="onCloseSharesModal()"></app-modal>
</ng-template>
零件:
onOpenSharesModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template, { class: 'modal-lg' });
}
测试:
it('should call onOpenSharesModal() when button clicked', () => {
const button = fixture.debugElement.query(By.css('button'));
const spy = spyOn(component, 'onOpenSharesModal');
button.triggerEventHandler('click', null);
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
});
我正在尝试测试组件:我已经能够测试onOpenSharesModal()
正在调用的组件,但我想测试它是否以modal
模板变量作为参数调用。我怎样才能做到这一点?
解决方案
您可以使用间谍来监视函数并检查作为参数传递的内容。假设您的组件被调用MyComponent
。在你的单元测试文件中你有(有点缩短,但你应该得到图片):
let myComponent: MyComponent = fixture.componentInstance;
// Set up a spy on your function
let spy = spyOn(myComponent, 'onOpenSharesModal').and.callThrough();
// After the function has been called somewhere in your component
expect(spy).toHaveBeenCalled();
// Check the arguments that were passed
expect(spy.calls.mostRecent().args[0]).toEqual(myComponent.modal);
这是假设modal
可以从您的组件访问模板变量。
推荐阅读
- java - Android - 在 html webview 中添加了图像,但图像不显示
- laravel - 为什么要在 laravel 中编译我们的 css 和 js 文件?它有什么好处?
- php - PHP 使用网络端口连接到 Redis 服务。RedisException:没有这样的文件或目录
- python - Pandas 数据框中的 SQL 查询等价物
- python - 如何避免类的属性错误?
- r - 如何将 (1) Yes 和 (2) No 更改为 0 和 1?
- macos - 将输出传送到另一个延迟命令时如何暂停主命令
- javascript - Typescript - 导入 Express 不起作用
- python - crontab 调用 shell 脚本出现导入错误
- acumatica - 如何更改销售订单页面中选项卡的顺序