I'm having trouble setting the value of a FormControl field called searchUser in my unit test.
In the below code "this.searchUser.value" is a form control. So in my test I did this so I could set it but didnt work:
homeComponent.searchUser = new FormControl();
homeComponent.searchUser.value = "ste";
This is the component method I'm testing (mapUsers):
mapUsers(users: User[]): User[] {
let results: User[] = [];
users.forEach((user: User) => {
let name = user.name.toLowerCase();
if (name.includes(this.searchUser.value.toLowerCase())) results.push(user);
});
return results;
}
This is my full unit test spec:
import { TestBed, async, inject } from "@angular/core/testing";
import { Observable } from "rxjs/Observable";
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHandler } from "@angular/common/http";
import { RouterTestingModule } from "@angular/router/testing";
import { FormControl } from "@angular/forms";
import { HomeComponent } from "./home.component";
import { HomeModule } from "./home.module";
import { UserService } from "../../services/user.service";
import { User } from "../../models/user.model";
import { HighlightDirective } from "../../directives/highlight.directive";
describe("HomeComponent", () => {
let userService;
let homeComponent;
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HomeModule,
RouterTestingModule.withRoutes([])
],
providers: [
HttpClient,
HttpHandler,
UserService
]
})
});
beforeEach(inject([UserService], service => {
userService = service;
fixture = TestBed.createComponent(HomeComponent);
homeComponent = fixture.componentInstance;
}));
it("should return array of users", async(() => {
// Arrange
const mockUsers: User[] = [{"name": "Steven"}];
homeComponent.searchUser = new FormControl();
homeComponent.searchUser.value = "ste";
// Act
const mockResponse = homeComponent.mapUsers(mockUsers);
fixture.detectChanges();
// Assert
expect(mockResponse).toEqual(mockUsers);
}));
});
Karma error I get:
Failed: Cannot set property value of [object Object] which has only a getter
You cannot directly set value of a form.You have to use either patchValue or setValue method like this