首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Unit Test:如果构造函数以Globals.ts文件作为参数,如何创建组件实例

问Angular Unit Test:如果构造函数以Globals.ts文件作为参数,如何创建组件实例
EN

Stack Overflow用户
提问于 2021-10-28 10:33:01
回答 1查看 40关注 0票数 0

我正在尝试为我的angular 6应用程序的Login组件编写单元测试。

login.component.ts文件具有以下构造函数

代码语言:javascript
复制
constructor(public global: Globals, private appService: AppService ) {
}

这里的Globals是一个普通的ts文件,它有一些跨组件使用的全局函数。AppService是一种服务。

我当前的spec.ts文件

代码语言:javascript
复制
describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports:[
        FormsModule,
        ReactiveFormsModule,
      ],
      providers:[
        AppService
      ]
    })
    .compileComponents();
  }));
   beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

这里的组件实例是未定义的。

谁能指导一下如何为这种情况创建TestBed配置模块,以及如何创建组件的实例?

EN

回答 1

Stack Overflow用户

发布于 2021-10-28 12:40:26

This是学习测试的一个很好的资源。

对于您的情况,我会嘲笑Globals和AppService的公共方法。

代码语言:javascript
复制
describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let mockGlobals: jasmine.SpyObj<Globals>;
  let mockAppService: jasmine.SpyObj<AppService>;

  beforeEach(async(() => {
    mockGlobals = jasmine.createSpyObj('Globals', [/*public methods you want to mock go here as an array of strings */]);
    mockAppService = jasmine.createSpyObj('AppService', [/ *public methods you want to mock go here as an array of strings */]);
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports:[
        FormsModule,
        ReactiveFormsModule,
      ],
      providers:[
        // provide mocks when component wants actual services
        { provide: Globals, useValue: mockGlobals },
        { provide: AppService, useValue: mockAppService }
      ]
    })
    .compileComponents();
  }));
   beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

createSpyObj有很多签名,你可以对它做更多的研究。我给出的链接还展示了如何模拟依赖关系的其他方法。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69752497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档