如何覆盖角度的按钮单击测试? (已附加Stackblitz)

问题描述 投票:1回答:2

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

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

  2. 使用事件处理程序订阅button

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

  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.';
            });
        }
  }

A complete working example here

它没有问题,您也可以检查一切是否正常。

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

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

enter image description here

我为实现按钮单击场景而编写的测试,

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();
  });
});

Working stackblitz with test cases here

(请查看hello.component.spec.ts

单击按钮,我已经覆盖并且可以使用

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

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

更新:经过一番搜索后,我发现我可以使用httpmock调用带参数的网址,但最终出现错误,因为],>

错误:对于标准“匹配网址:https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp”,找不到。

您也可以看到Modified stackblitz with httpMock here...

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

非常感谢。

我正在制作一个非常简单的应用程序,它具有一个输入框和一个按钮。输入用于输入电子邮件和事件处理程序的订阅按钮输入电子邮件并单击按钮,将创建一个api ...

javascript angular typescript unit-testing karma-jasmine
2个回答
1
投票

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


0
投票

实际上,最好重构代码并使之更易于测试。但是提供的示例仍然可以进行测试。验证传递的参数以及参数是否正确的想法,然后以可观察到的方式返回可预测的响应。

© www.soinside.com 2019 - 2024. All rights reserved.