0

我想在不触及外部模板的情况下为我的组件编写一些单元测试。但我不知道如何模拟我的组件所依赖的服务。

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 类的所有属性添加到我的模拟中,如urlparamsqueryParams等。我该如何避免这种情况?

4

1 回答 1

3

完全符合原始类接口的服务模拟可以按原样提供:

myComponent = new MyComponent(stub);

如果一个 mock 部分符合接口并且没有通过类型检查,则可以使用类型断言:

myComponent = new MyComponent(<AnotherService>stub);

当类型根本不匹配时,可以使用双重断言:

myComponent = new MyComponent(<AnotherService><any>stub);
于 2017-08-24T11:03:45.750 回答