我想在不触及外部模板的情况下为我的组件编写一些单元测试。但我不知道如何模拟我的组件所依赖的服务。
my-component.ts
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent {
constructor(public service: AnotherService) {}
}
my-component.spec.ts
let component: MyComponent;
beforeEach(() => {
myComponent = new MyComponent(null);
});
another.service.ts
@Injectable()
export class AnotherService {
toto: string;
}
那行得通,但null
我不想模拟AnotherService
,所以我创建了一个模拟服务:
class AnotherServiceStub {
toto: string
}
和
myComponent = new MyComponent(<AnotherService> new AnotherServiceStub());
但是以ActivatedRoute为例,
component = new MyComponent(<ActivatedRoute> {});
不起作用。Typescript 要求我将 ActivatedRoute 类的所有属性添加到我的模拟中,如url、params、queryParams等。我该如何避免这种情况?