Starting with Jest spectator, I try to test a function that is called in another. The purpose of the test is to know whether or not the function was called correctly.
I tried to follow the documentation here: https://jestjs.io/docs/expect#tohavebeencalled
For information, the function to be called manages the emission of an EventEmitter, and this method is private.
Here's the .ts code:
private emitPiecesJointes(): void {
this.piecesJointes.emit(this.pieceJointesUploaded);
}
emitPiecesJointes() is called like this:
public fileDeleted(index: number): void {
this._piecesJointes.splice(index, 1);
this.emitPiecesJointes();
}
Here's the test I try to run with the wrong code:
describe('BlablaComponent', () => {
let spectator: Spectator<BlablaContratComponent>;
const createComponent = createComponentFactory({
component: BlablaContratComponent,
schemas: [NO_ERRORS_SCHEMA],
});
it('it should issue an attachment', () => {
const emitPiecesJointes = jest.fn();
spectator.component.fileDeleted(1);
expect(emitPiecesJointes).toHaveBeenCalled();
});
Thanks for help
There problem you are having is that you are building a mock into a local variable and not doing anything with it.
const emitPiecesJointes = jest.fn();creates a mock, but doesn't actually do anything else. This would be appropriate to replace a public function like this:spectator.component.fileDeleted = jest.fn();, but won't work for a private function.To mock a private function, replace that line with the following:
const emitPiecesJointes = jest.spyOn(BlablaContratComponent.prototype as any, "emitPiecesJointes");