本文介绍了如何覆盖角度的按钮单击测试? (附有Stackblitz)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个非常简单的应用程序,它具有一个输入框和一个按钮.

I am making a very simple application which has one input box and a button.

  1. 输入用于输入电子邮件

使用事件处理程序订阅按钮

Subscribe button with event handler

输入电子邮件并单击按钮将进行api调用,(此方法有效)

Entering email and click over the button will make an api call, (This method works)

  subscribeEmail() {
    this.error = '';


        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }

此处是一个完整的工作示例

没有问题,您还可以检查一切是否正常.

There is no issues with it and you can also check everything works fine.

要求:我需要涵盖此按钮单击和带有参数的http调用的测试用例.

Requirement: I am in the need to cover test case for this button click and the http call with params.

我无法编写测试用例,这表明带有params的http调用未涵盖测试.

I am unable to write the test case and it is showing that the tests are not covered for the http calls with params.

我为实现按钮单击情况而编写的测试,

The tests that I have written so for for achieving the button click scenario like,

describe('HelloComponent', () => {

  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', (done: DoneFn) => {

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    done();
  });
});

在此处使用测试用例进行stackblitz

(请查看 hello.component.spec.ts )

对于按钮单击,我已经进行了介绍,并且可以正常工作

For button click, I have covered and it works

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

能否请您帮我实现覆盖带有http调用并带有参数的按钮单击的测试用例的结果?

Could you please help me to achieve the result of covering the test case for the button click that has http call with params?

更新:经过一番搜索后,我发现我可以使用httpmock来调用带有参数的网址,但是我最终得到的错误是,

Update:After some search I have found that I can use httpmock to call the url with params but I am ending up with error as,

您还可以在此处查看> 使用httpMock修改后的stackblitz ... >

You can also see the Modified stackblitz with httpMock here...

毕竟,我只能发表这篇文章,所以请考虑这个问题并提供正确的解决方案.

After all try only I am making this post so please consider this question and provide right solution.

非常感谢.

推荐答案

这是一个很长的问题,我知道您已经花了很多时间来创建它.因此,我还花了一些时间来重构代码以使其按照最佳实践进行制作.这将需要将您的代码作为服务进行拆分,并使代码更好地用于单元测试. (组件服务的单元测试)

That was a very long question, I understand that you have put a lot of time to create it. So, I have also put some time to refactor the code to make it as per the best practices. This would require to split your code as a service and make the code better for Unit Testing. (Unit testing for component & service)

  1. 创建一个服务,例如MyService并将http代码移入其中.这将帮助您分别对componentservice进行单元测试.我创建如下:
  1. Create a service such as MyService and move the http code into it. It would help you unit test component and service separately. I created as below:
export class MyService {
  mailChimpEndpoint = 'https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55&amp';
  constructor(private _http: HttpClient) {}

  submitForm(email: string){
    const params = new HttpParams()
                .set('EMAIL', email)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
    const mailChimpUrl = this.mailChimpEndpoint + params.toString();

    return this._http.jsonp<MailChimpResponse>(mailChimpUrl, 'c')
  }
}
  1. 为组件您可以在堆栈闪电战中看到这里.仔细阅读重构后的代码和我如何根据情况介绍所有案例.正如我在您先前的问题中已解释的那样,您可以测试MatSnackBar调用

  1. Create a Unit test for component as you can see here in the stackblitz . Take a good look at refactored code & how I have covered all cases depending on the scenario. As I have already explained in your previous question, you can test MatSnackBar calls

类似地,您可以参考我的一篇文章旨在测试服务

这篇关于如何覆盖角度的按钮单击测试? (附有Stackblitz)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:02