2017-08-23 10 views
0

私は、外部テンプレートに触れずにコンポーネントの単体テストを書いてみたいと思います。しかし、私のコンポーネントが依存しているサービスを模擬する方法はわかりません。TestBedを使用せずにサービスを模擬する方法

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

ではなく、私は AnotherServiceをモックとしたい nullの作品
@Injectable() 
export class AnotherService { 
    toto: string; 
} 

ので、私はモックサービスを作成しました:

class AnotherServiceStub { 
    toto: string 
} 

myComponent = new MyComponent(<AnotherService> new AnotherServiceStub()); 

しかしとActivatedRoute例えば、

component = new MyComponent(<ActivatedRoute> {}); 

は動作しません。活字体がURLのparamsqueryParamsように私のモックにActivatedRouteクラスのすべての属性を追加するために私に尋ねた、などがどのように私はそれを避けることができますか?

+1

'myComponent = new MyComponent({toto: '何か'});'? – jonrsharpe

+0

@jonrsharpeありがとうが、私はTypescriptを使用するため、パラメータの型をチェックするので動作しません。 –

+0

あなたのモックが同じ署名を持っていればうまくいきます。これは、テストベッドの提供者にモックを注入するのと同じです。抽象的な例はあまりありませんか? – jonrsharpe

答えて

0

サービスであるように十分に提供することができる元のクラスのインタフェースに適合していることをモック:

myComponent = new MyComponent(stub); 

モックが部分的インターフェースに準拠し、タイプチェックを通過しない場合、type assertionを使用することができる。

タイプが全く一致しない
myComponent = new MyComponent(<AnotherService>stub); 

、二重のアサーションを使用することができます。

myComponent = new MyComponent(<AnotherService><any>stub); 
+0

ありがとう、ダブルアサーションはうまくいきます –

関連する問題