When testing the functionality of the component.navigateTo()
method, it is important not to use the spyOn
function on this method. Using spyOn
will prevent the window.parent.postMessage()
from being called. Instead, apply the spyOn
function to the window.parent.postMessage()
method.
For more information, refer to the Default Spy Strategy
By default, the spy strategy is set to .and.stub()
, which will return undefined
when the spy is invoked.
The correct test code should look like this:
example.component.ts
:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'example',
})
export class ExampleComponent implements OnInit {
ngOnInit() {}
navigateTo = (): void => {
window.parent.postMessage('NESTED_NAVIGATION', 'target_origin');
};
}
example.component.test.ts
:
import { ExampleComponent } from './example.component';
describe('70440045', () => {
it('should post message on click', async () => {
const component = new ExampleComponent();
let postMessageSpy: jasmine.Spy<(message: any, targetOrigin: string, transfer?: Transferable[]) => void> = spyOn(
window.parent,
'postMessage',
);
component.navigateTo();
expect(postMessageSpy).toHaveBeenCalledWith('NESTED_NAVIGATION', 'target_origin');
});
});
We have explicitly defined the signature of postMessage
to prevent TypeScript errors.
Test results:
Chrome Headless 95.0.4638.69 (Mac OS 10.15.7): Executed 1 of 1 SUCCESS (0.008 secs / 0.004 secs)
TOTAL: 1 SUCCESS
=============================== Coverage summary ===============================
Statements : 94.12% ( 16/17 )
Branches : 100% ( 0/0 )
Functions : 62.5% ( 5/8 )
Lines : 100% ( 13/13 )
================================================================================
Dependencies versions:
"@angular/core": "~11.0.3",
"@angular/cli": "~11.0.3",
"karma-jasmine": "~4.0.0",
"karma": "~5.1.0",
"jasmine-core": "^3.10.1"