2

I have a save method.

public saveJob(formData: any, redirect: boolean = false): Observable<any> {
    if (!this.checkJobValidity()) {
        return Observable.of(null);
    }
    return this.service.edit(this.job)
        .do((data) => {
            this.job = data;
        })
        .switchMap(() => this.service.addCustomer(this.job.id, this.customers)
            .do(customers => {
                this.customers = customers;
            }))            
        .switchMap(() => this.saveJobComment())
        .switchMap(() => this.saveJobTasks())
        .switchMap(() => this.saveJobProducts(this.jobProducts))
        .finally(() => {
            const hasInvoiceNumbers: boolean = !!this.jobInvoiceNumbers.find(j => !!j.invoiceNumber);
            console.log(this.job.phase && this.isXeroCustomer && !hasInvoiceNumbers);
            if (this.job.phase === 'INVOICE' && this.isAutoCustomer) {
                this.createAutoInvoice();
            } else if (isManualInvoice) {
                this.createManualInvoice();
            }
            this.messageService.show({
                template: 'plain_string',
                level: 'success',
                context: {message: `Job ${this.job.code} saved successfully.`},
                flash: redirect,
                timeout: this.config.ALERT_TIMEOUT
            });
            if (redirect) {
                this.router.navigate(['/jobs', this.job.id]);
            }
        });
}

I wanted to write unit test see if the auto invoicing works correctly. ie; the finally block. I have mocked up this.service.edit and this.service.addCustomer and I am expecting if I mock all the switchMap cases, it would finally end up in my finally block and I can test it. Is that the way I should proceed?

Josf
  • 776
  • 1
  • 8
  • 21

1 Answers1

0

I think if you take the code you have in your finally block and extract it into a method, you can test your code more easily. You should be able to detect a hasBeenCalled against a spy on that method in the finally block. Then, obviously, you can unit test the rest of the code against the new method you created.

Conner Smith
  • 383
  • 4
  • 7