Angular – 在提交时测试服务订阅

huangapple go评论94阅读模式
英文:

Angular - Test service subscribe on submit

问题

我如何测试提交操作的订阅事件覆盖率?我有以下代码:

onSubmit() {
    this.myService.myMethod(value)
      .subscribe((result: any) => {
        console.log(result);
      },
        error => {
          console.log(error);
        },
        () => {
          console.log('completed');
        }
      );
}

测试

it('应该测试提交',
    inject([myService, XHRBackend], (myService: any, mockBackend: any) => {
      const mockResponse = {
        error: false,
        msg: `Completed`
      };
      mockBackend.connections.subscribe((connection: any) => {
        connection.mockRespond(new Response(new ResponseOptions({
          body: JSON.stringify(mockResponse)
        })));
      });
      myService.myMethod().subscribe(() => { });
    }));

我的测试覆盖率显示我没有测试订阅部分。

英文:

How can i coverage test of submit action with subscribe event? i have this:


onSubmit() {
    this.myService.myMethod(value)
      .subscribe((result: any) => {
        console.log(result);
      },
        error => {
          console.log(error);
        },
        () => {
          console.log('completed);
        }
      );
}

test

it('should test submit',
    inject([myService, XHRBackend], (myService: any, mockBackend: any) => {
      const mockResponse = {
        error: false,
        msg: `Completed`
      };
      mockBackend.connections.subscribe((connection: any) => {
        connection.mockRespond(new Response(new ResponseOptions({
          body: JSON.stringify(mockResponse)
        })));
      });
      myService.myMethod().subscribe(() => { });
    }));

My test coverage show that i haven't tested the subscribe lines.

答案1

得分: 1

onSubmit组件代码中存在一些缺陷。当你只是使用console.log等方式时,你如何测试结果呢?你需要处理某种标志并显示/隐藏旋转图标或提供一些错误/成功消息。然后你可以使用errorsuccess来测试该函数。例如:

onSubmit() {
    this.showSpinner = true;
    this.myService.myMethod(value)
      .subscribe((result: any) => {
        this.msg = 'success';
      },
        error => {
          this.msg = 'error';
        },
        () => {
          this.showSpinner = false;
        }
      );
}

测试文件中:

class MySvcMock{
  myMethod() { return of('someVal')}
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
       providers: [{provide: MyService, useClass: MySvcMock}]        
    }).compileComponents();
...
...

it('should set success msg on submit',() => {
   component.msg = '';
   component.onSubmit();
   expect(component.msg).toBe('success');
   expect(component.showSpinner).toBeFalsy();
})

it('should set error msg on submit error',() => {
   component.msg = '';
   spyOn(component.myService,'myMethod').and.returnValue(throwError('some error msg'));
   component.onSubmit();
   expect(component.msg).toBe('error');
   expect(component.showSpinner).toBeFalsy();
})

你可以参考我的一系列文章,这些文章可以帮助你更熟悉Karma。

  1. Karma入门。查看文章底部的链接
  2. 这篇文章将帮助你在这种情况下进行测试
英文:

There are few flaws in the component code of onSubmit. How can you test the outcome when you are just doing console.log etc. You need to handle some kind of flag and show/hide spinner or provide some error/success message. Then you can test the function with error and success. For example:

onSubmit() {
    this.showSpinner = true;
    this.myService.myMethod(value)
      .subscribe((result: any) => {
        this.msg = 'success';
      },
        error => {
          this.msg = 'error';
        },
        () => {
          this.showSpinner = false;
        }
      );
}

in test file:

class MySvcMock{
  myMethod() { return of('someVal')}
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
       provider: [{provide: MyService, useClass: MySvcMock}]        
    }).compileComponents();
...
...

it('should set success msg on submit',()=>{
   component.msg = '';
   component.onSubmit();
   expect(component.msg).toBe('success');
   expect(component.showSpinner).toBeFalsy();
})

it('should set error msg on submit error',()=>{
   component.msg = '';
   spyOn(component.myService,'myMethod').and.returnValue(throwError('some error msg'));
   component.onSubmit();
   expect(component.msg).toBe('error');
   expect(component.showSpinner).toBeFalsy();
})

You can refer to my series of article which can help you get more familiar with Karma.

  1. Intro to Karma. check the links at the bottom of article
  2. This is the one which will help you in this scenario

huangapple
  • 本文由 发表于 2020年1月3日 14:04:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定