Mock static method inside a Typescript class in an Angular test with Jest

Viewed 4414

I want to mock a simple Typescript class with a static method in my component's test. I'm using Angular 8 and jest 24.9.0 After trying different approaches and read the jest documentation multiple times, it's still not working ...

Here is my code :

amazing.component.ts

import { Component, OnInit } from '@angular/core';
import { SimpleClass } from '../SimpleClass';

@Component({
    selector: 'app-amazing',
    templateUrl: './amazing.component.html',
    styleUrls: ['./amazing.component.scss']
})
export class AmazingComponent implements OnInit {
    message = 'default msg';
    constructor() {}

    ngOnInit() {
        this.message = SimpleClass.staticMethod('Bob');
    }
}

amazing.component.html

<p>{{ message }}</p>

SimpleClass.ts

export class SimpleClass {
    static staticMethod(myParam: string) {
        return 'Hello ' + myParam;
    }
}

amazing.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AmazingComponent } from './amazing.component';
import { By } from '@angular/platform-browser';

describe('AmazingComponent', () => {
    let component: AmazingComponent;
    let fixture: ComponentFixture<AmazingComponent>;

    jest.mock('../SimpleClass', () => ({
        default: class {
            public static staticMethod(param) {
                return 'MOCK MSG ' + param;
            }
        }
    }));

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AmazingComponent]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AmazingComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should display the message transformed', async(() => {
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            const message = fixture.debugElement.query(By.css('p'));
            expect(message.nativeElement.textContent).toEqual('MOCK MSG Bob');
        });
    }));
});

Result :

Error: Uncaught (in promise): Error: expect(received).toEqual(expected) // deep equality

Expected: "MOCK MSG Bob"
Received: "Hello Bob"

It seems that my mock is not working, but I don't understand the reason ... Any idea ?

======================================

PROBLEM SOLVED !

I had to put my jest.mock outside the describe, just after imports. And mock the implementation of the desired function by casting the mocked object in jest.Mocked.

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AmazingComponent } from './amazing.component';
import { By } from '@angular/platform-browser';
import { SimpleClass } from '../SimpleClass';

jest.mock('../SimpleClass');

describe('AmazingComponent', () => {
    let component: AmazingComponent;
    let fixture: ComponentFixture<AmazingComponent>;
    const MockSimpleClass = SimpleClass as jest.Mocked<typeof SimpleClass>;
    MockSimpleClass.staticMethod.mockImplementation((param) => 'MOCK MSG ' + param);

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AmazingComponent]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AmazingComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should display the message transformed', async(() => {
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            const message = fixture.debugElement.query(By.css('p'));
            expect(message.nativeElement.textContent).toEqual('MOCK MSG Bob');
        });
    }));
});

0 Answers
Related