使用 Jasmine 和 Karma 测试 HTML 按钮

Testing HTML Button with Jasmine & Karma

contact.component.html

<div>
    {{ text }}
</div>

<form id="contact-form" [formGroup] = "contactForm" novalidate>
    <div class = "form-group">
        <label class = "center-block">Name:
            <input class = "form-control" formControlName = "name">
        </label>
        <label class="center-block"> Email:
            <input class="form-control" formControlName="email">
        </label>
        <label class="center-block"> Text:
            <input class="form-control" formControlName="text">
        </label>
    </div>
    <button id="MyButton" click="onSubmit()">Click Me!</button>
</form>

contact.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
    templateUrl : './contact.component.html',
    styleUrls: ['./contact.component.sass']
})

export class ContactComponent {
    text = 'contact Page';
    contactForm: FormGroup;

    contact = {
        name: '',
        email: '',
        text: ''
    };
    submitted = false;

    constructor() {

    }

    onSubmit(): void {
        this.submitted = true;
    }
}

contact.component.spec.ts

import { BrowserModule, By } from '@angular/platform-browser';
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { DebugElement } from '@angular/core';


import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ContactComponent } from 'src/component/contact/contact.component';




describe('ContactComponent', () => {
    let comp: ContactComponent;
    let fixture: ComponentFixture<ContactComponent>;
    let de: DebugElement;
    let el: HTMLElement;
    beforeEach(async(() => {
        TestBed.configureTestingModule({
        declarations: [
            ContactComponent
        ],
        imports: [
            BrowserModule,
            FormsModule,
            ReactiveFormsModule
        ]
        }).compileComponents().then( () => {
            fixture = TestBed.createComponent(ContactComponent);
            comp = fixture.componentInstance;
        });
    }));

    it('should call the onSubmit method 1 times', async( () => {
        fixture.detectChanges();

        spyOn(comp, 'onSubmit');
        document.getElementById('MyButton').click();

        expect(comp.onSubmit).toHaveBeenCalledTimes(1);
    }));

这些是我的文件。我想测试我的 onSubmit() 函数。我有一个带有按钮 id='MyButton' 的 HTML 页面。如果我单击按钮,将调用 OnSubmit() 函数。

如果我运行

ng test

我明白了:

It says: "Expected spy onSubmit to have been called once. It was called 0 times."

那么,如果我使用 html 按钮,如何检测要调用的 onSubmit 函数?

有些地方设置不当,但主要是您设置 click 活动的方式。应该是 (click)="onSubmit()" 而不是 click="onSubmit()".

此外,我会将您设置间谍的方式更改为以下内容:

let onSubmitSpy = spyOn(component, 'onSubmit').and.callThrough();
expect(onSubmitSpy).not.toHaveBeenCalled();

// more code ..
expect(onSubmitSpy).toHaveBeenCalledTimes(1);

Here is a working stackblitz.