Angular,对通过接口创建服务的组件进行单元测试 [英] Angular, unit testing a component that creates a service via an interface

查看:36
本文介绍了Angular,对通过接口创建服务的组件进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此组件可在本地创建服务

Given this component that creates a service locally

@Component({
    <removed for clarity>
    providers: [
        { provide: 'IMyService', useClass: MyService },
    ]
})
export class MyComponent implements OnInit, OnDestroy, AfterViewInit
{
    constructor(private data: IMyService){}
}

我一直在尝试在单元测试中提供服务,诸如此类

I've been trying to supply the service in the unit test, something like this

beforeEach(async(() =>
{
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [
            { provide: 'IMyService', useClass: MockMyService },
        ]
    })
    /*
        .overrideProvider('IMyService', { useValue: MockMyService })
        .overrideComponent(MyComponent, {
        set: {
            providers: [
                { provide: 'IMyService', useClass: MockMyService }
            ]
        }
    })
   */
.compileComponents();

注释掉的东西是我尝试过的东西.

The commented out bits being things I've tried.

但是我不断收到此消息

Failed: Can't resolve all parameters for MyComponent: (?)

我在这里想念什么?

推荐答案

我想我已经找到了答案

https://stackoverflow.com/a/47451244/220545

constructor(
@Inject('IMyService') private data: IMyService,

正如评论所说,这对我有用.没有Inject,应用程序运行良好.但是,通过ng测试,似乎需要Inject.我使用的是Angular 6"

As the comment says, "This works for me. Without Inject, the app is working fine. However, with ng test, it seems Inject is required. I am using Angular 6"

此外,在单元测试中只需要overrideProvider,但对于在组件范围内创建的提供者来说确实需要它

In addition, you only need overrideProvider in the unit test, but you do need it for providers that are created in the component scope

这篇关于Angular,对通过接口创建服务的组件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆