私は、外部テンプレートに触れずにコンポーネントの単体テストを書いてみたいと思います。しかし、私のコンポーネントが依存しているサービスを模擬する方法はわかりません。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、のparams、queryParamsように私のモックにActivatedRouteクラスのすべての属性を追加するために私に尋ねた、などがどのように私はそれを避けることができますか?
'myComponent = new MyComponent({toto: '何か'});'? – jonrsharpe
@jonrsharpeありがとうが、私はTypescriptを使用するため、パラメータの型をチェックするので動作しません。 –
あなたのモックが同じ署名を持っていればうまくいきます。これは、テストベッドの提供者にモックを注入するのと同じです。抽象的な例はあまりありませんか? – jonrsharpe