【问题标题】:Testing function submit() in Component + Service, using Angular 5使用 Angular 5 在组件 + 服务中测试函数 submit()
【发布时间】:2018-06-04 08:24:56
【问题描述】:

我需要测试函数提交。我有这个代码:

onAddProd() {
    this.areWeWaiting = true;
    let newProd= new Product(
      this.addProdForm.value
    );
    this.ws.createProduct(newProd).subscribe( //createProduct is function service
      result => {
        if (result === true) {
          this.router.navigate(['/home']);
        } else {
          this.areWeWaiting = false;
        }
      },
      error => {
        this.areWeWaiting = false;
      }
    );
  }

我基本上需要测试。 - 如果结果为真,应该导航到/home

你能给我建议吗?

【问题讨论】:

    标签: angular unit-testing testing jasmine


    【解决方案1】:

    首先要做的事情:你的函数中有很多事情要做。独立测试所有服务是个好主意。

    尤其是到/home路由Route 模块管理,并且必须在单独的文件中进行测试。更多详情请关注here

    测试函数的一个关键点是能够模拟所有被调用的服务。您通常必须在 describe 函数之前声明这些模拟

    let wsMock
    let routerMock
    
    describe('MyComponentUnderTest', () => {
      let component: MyComponentUnderTest
      let fixture: ComponentFixture<MyComponentUnderTest>
      ...
    })
    

    接下来,您必须启动模拟并覆盖它在测试期间应返回的值:

    beforeEach(async(() => {
      wsMock = jasmine.createSpyObj('ws', ['createProduct'])
      wsMock.createProduct.and.returnValue(of(SOME_VALUE_THAT_YOU_HAVE_TO_SET))
    
      routerMock = jasmine.createSpyObj('Router', ['navigate'])
    }))
    

    最后但同样重要的是,您的 beforeEach 函数由测试模块的配置结束,您必须在其中注入您的模拟服务:

    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      schemas: [ NO_ERRORS_SCHEMA ],
      providers: [
        {provide: ws, useValue: wsMock},
        {provide: Router, useValue: routerMock}
      ]
    })
    .compileComponents()
    

    这就是样板。让我们继续测试:

    it('should create a product', () => {
      component.onAddProd()
      expect(component.areWeWaiting).toBeTruthy()
    })
    

    您可以访问Angular web site了解有关组件测试的更多详细信息。

    【讨论】:

    • 是的,我正在测试我的组件,例如表单。我只需要测试这个功能。测试此提交功能的最佳方法是什么?
    • 其实,这正是我向您解释的内容:单独测试所有服务/组件,然后为该函数调用的所有服务创建模拟,然后测试您的函数。测试areWeWaiting 的真假似乎是个好主意。
    【解决方案2】:

    在 beforeEach 函数中声明

    Providers: [
    ....
    { provide: Router, useValue: jasmine.createSpyObj("router", ["navigate"]) }
    ]
    const injector = getTestBed();
    router = injector.get(Router);
    

    在函数中,

    expect(router.navigate).toHaveBeenCalledWith(["/home"]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      相关资源
      最近更新 更多