【问题标题】:angular 4 unit test issue - I want to set a form FormControl fields value角度 4 单元测试问题 - 我想设置表单 FormControl 字段值
【发布时间】:2017-09-06 14:00:59
【问题描述】:

我在单元测试中设置名为 searchUser 的 FormControl 字段的值时遇到问题。

在下面的代码中,“this.searchUser.value”是一个表单控件。 所以在我的测试中我这样做了,所以我可以设置它但没有工作:

homeComponent.searchUser = new FormControl();
homeComponent.searchUser.value = "ste";

这是我正在测试的组件方法(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; 
  }

这是我的完整单元测试规范:

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

});

我得到的业力错误:

失败:无法设置 [object Object] 的属性值,它只有一个 吸气剂

【问题讨论】:

标签: angular unit-testing jasmine testbed


【解决方案1】:

您不能直接设置表单的值。您必须像这样使用 patchValue 或 setValue 方法

homeComponent.searchUser.patchValue({[formControlName]:[formControlValue]})

【讨论】:

  • 在我的情况下你的意思是这样的:homeComponent.searchUser.patchValue({["searchUser"]:["ste"]})
  • @AngularM 不,这在语法上没有意义;它将是一个计算的属性名称和一个数组值。我认为括号是用来表示占位符的。
  • patchvalue 和 setvalue 在表单实例上可用,而不是在 formcontrol 表单实例上使用 formbuilder 或使用 new FormGroup() 创建的意思
  • 是的,括号是 patchvalue 方法中的占位符,您将带有键的对象作为表单控件名称和值作为表单控件值传递
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 2014-12-09
  • 1970-01-01
  • 2017-04-25
相关资源
最近更新 更多