In the last blog post I showed how you could extend NgbModal to make a Modal Service, letting you re-use modal dialogs easily from within your Angular components.
Even though its not always that much fun, I like to try and keep testability in mind when writing code… and, I’ll admit it, sometimes I gloss over javascript/typescript because its a little … different.
Unit Testing
Suppose that you have a Yes/No dialog in your service that returns true if the dialog was closed with the “Yes” button, and otherwise it returns false (either from the “No” button, the X in the corner, or pressing escape to close the dialog).
Since NgbModalService is doing the heavy lifting for us by actually opening the dialog, we need to hook in to it so we can “fake” opening the dialog and return a new instance of it. We can do this by spying on NgbModalService’s open function, calling a fake that returns a new instance of the dialog we want to test. Since the spy is scoped to the test, we don’t have to worry about it messing up any other dialogs we want to test later.
The call is a promise and we await it, execution of the test will wait until the dialog is closed… which is kind of a problem, since we want to run the test without any user interaction. Luckily, the fake will receive the same parameters that the real call will, so we can then hook in to the beforeDismiss function that we set up to handle the modal dialog closing via the X or the escape button.
Finally, we want to make sure that the fake returns an instance of NgbModalRef. The componentInstance property is the reference to our created dialog, allowing us to manipulate the dialog and check the results in the end.
Since you have a handle to the dialog, you can set properties (if you have a more complicated form-like dialog) and close the dialog using the close method, thereby simulating success or cancelation. Its the same process, except instead of calling beforeDismiss you can call the close method on the dialog, providing it with your desired result:
Now that your dialog service is tested, you can move on with your day, feelin’ good.