如何通过mat-dialog-close或其他方式对MatDialog是否关闭进行单元测试 [英] How do I unit-test that MatDialog is closed, by mat-dialog-close or otherwise
问题描述
我有一个简单的组件,该组件将通过 MatDialog 显示为对话框窗口. .在该组件的模板中,一个按钮标记为 mat-dialog-close 属性,该属性应关闭对话框窗口.
I have a simple component, which will be displayed as a dialog window by MatDialog. In the template of that component, one button is labelled with mat-dialog-close attribute, which should close the dialog window.
如何在单击按钮时对对话框是否确实关闭进行单元测试?而且,mat-dialog-close可以接受参数并将其传递给打开对话框的任何人.如何验证是否传递了正确的值?
How can I unit-test that the dialog is indeed closed when clicking on the button? Moreover, mat-dialog-close can take an argument and pass it to whomever opened the dialog. How can I verify that the correct value is passed?
这与测试MatDialog
机器无关,而是与将其正确连接到组件有关.从测试的POV中,我不太关心对话框是通过mat-dialog-close
按钮还是通过精心设置的调用this.dialogRef.close()
的超时来关闭.在后一种情况下,我可以模拟注入的dialogRef
并监视调用close
的情况,但是使用mat-dialog-close
更为方便,所以我要坚持这一点.
It's not about testing the MatDialog
machinery, more about correctly attaching it to the component. From the test's POV I couldn't care less if the dialog was closed by the button with mat-dialog-close
or by carefully set timeout that calls this.dialogRef.close()
. In the latter case I could mock the injected dialogRef
and spy on calling close
, but using mat-dialog-close
is much more convenient, so I'd like to stick to this.
通常我会使用 TestBed.createComponent 来创建组件,也许是这样必须以某种方式进行更改.
Normally I'd use TestBed.createComponent to create components, maybe this would have to be changed somehow.
推荐答案
我参加聚会有点晚了,但这是我的工作方式.如上面的评论中所述,需要对注入的MatDialogRef进行监视. OP可能遗漏的部分是,当从组件内部手动调用this.dialogRef.close()
时,具有mat-dialog-close
属性AS WELL AS的材质将调用该场景.
I'm a bit late to the party, but here's how I did this. As mentioned in the comments above, a spy on the injected MatDialogRef is needed. The part that OP may have missed is that behind the scenes that will be called by material with the mat-dialog-close
attribute AS WELL AS when this.dialogRef.close()
is called manually from within the component.
我的组件仅使用以下模板:
My component only uses the following template:
<button mat-button mat-dialog-close>Cancel</button>
并且以下测试通过了:
it('should close the component if cancel is clicked', () => {
mockDialogRef.close.calls.reset();
page.cancelButton.click();
expect(mockDialogRef.close).toHaveBeenCalled();
});
(如如果我调用一个函数并执行this.dialogRef.close()
,则此完全相同的测试通过.
This exact same test passes if instead I call a function and execute this.dialogRef.close()
.
虽然我没有测试通过的值,但是OP确实询问了这一点.这样的事情应该可以解决问题:
While I am not testing a value passed, the OP did ask about that. Something like this should do the trick:
在模板中:
<button mat-button [mat-dialog-close]="true">Cancel</button>
现在正在测试中:
it('should close the component and pass back correct data if cancel is clicked', () => {
mockDialogRef.close.calls.reset();
page.cancelButton.click();
expect(mockDialogRef.close).toHaveBeenCalledWith(true);
});
我希望这会有所帮助.
这篇关于如何通过mat-dialog-close或其他方式对MatDialog是否关闭进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!