为了在Jest中成功测试一个service,需要用到Jest的mock功能,将该service的构造函数mock掉。下面是示例代码:
// 实际的service代码
@Injectable()
export class MyService {
constructor() {}
getSomething(): Observable {
// get something
}
}
// 在测试中,将构造函数mock掉
const mockService = {
getSomething: jest.fn().mockReturnValue(of({}))
};
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [
{ provide: MyService, useValue: mockService } // 将service替换成mockService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在上面的示例中,我们将MyService中的构造函数mock掉,并把mockService注入到了测试中。这样,当测试中需要调用MyService中的getSomething方法时,会调用mockService中的方法,而不会出现构造函数相关的问题。