Я хочу смоделировать простой класс Typescript с помощью метода stati c в тесте моего компонента. Я использую Angular 8 и jest 24.9.0. После попытки разных подходов и многократного чтения документации jest, она все еще не работает ...
Вот мой код:
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.spe c .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');
});
}));
});
Результат:
Error: Uncaught (in promise): Error: expect(received).toEqual(expected) // deep equality
Expected: "MOCK MSG Bob"
Received: "Hello Bob"
Кажется, что мой макет не работает, но я не понимаю причину ... Есть идеи?
============================================
ПРОБЛЕМА РЕШЕНА!
Мне пришлось поместить jest.mock вне описания сразу после импорта. И смоделируйте реализацию желаемой функции, приведя макетированный объект в 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');
});
}));
});