If you want to perform unit testing on the module, it is recommended to utilize ReactiveForms instead of Template driven forms as suggested in the comment. I have refactored the code and provided an example based on the snippet you shared. Here is a possible solution:
Here is one approach to refactor your code to ensure its functionality:
Your component:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-unit-test',
template: `
<p>Works</p>
`,
styleUrls: ['./unit-test.component.css']
})
export class UnitTestComponent {
public addCred: boolean = true;
public credName: any;
form: FormGroup = new FormGroup({
name: new FormControl('', [])
});
constructor() {}
public addMachineCredential(credentialForm: FormGroup) {
this.addCred = true;
this.credName = credentialForm.controls.name.value;
}
}
Your spec file:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { UnitTestComponent } from './unit-test.component';
fdescribe('UnitTestComponent', () => {
let component: UnitTestComponent;
let fixture: ComponentFixture<UnitTestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [UnitTestComponent],
imports: [FormsModule, ReactiveFormsModule]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UnitTestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should add machine credential', () => {
component.form.controls.name.setValue('name');
component.addMachineCredential(component.form);
expect(component.addCred).toBe(true);
expect(component.credName).toBe('name');
});
});
Keep in mind that your component module must declare ReactiveFormsModule, so..
Your module:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { UnitTestComponent } from './Questions/unit-test/unit-test.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
UnitTestComponent,
FormsModule,
ReactiveFormsModule
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I hope this explanation proves helpful.