Expect(component).toBeTruthy()失败

时间:2019-07-23 11:54:40

标签: angular unit-testing

我想为一个组件编写单元测试。第一次测试失败, 出现此错误:

  

错误:期望未定义是真实的。

it块输出错误:

it('should create', () => {
    expect(component).toBeTruthy();
  });

登录模板:

<h3>Login</h3>
<form class="form form-group" (ngSubmit)="onSubmit()">
  <div class="row">
    <label for="email" class="login-form-label col-4">Email:</label>
    <input ngModel [(ngModel)]="email" name="email" (ngModelChange)="validateEmail()" type="email" id="email" class="col-3 form-control">
    <span class="error col-sm-4">{{ this.emailErr }}</span>
  </div>
  <br>
  <div class="row">
    <label for="password" class="login-form-label col-4">Wachtwoord:</label>
    <input ngModel [(ngModel)]="password" name="password" (ngModelChange)="validatePassword()" type="password" id="password" class="col-3 form-control">
    <span class="error col-sm-4">{{ this.passwordErr }}</span>
  </div>
  <input type="submit" [disabled]="!isValid()" value="Login" class="login-button col-1">
</form>

我尝试过:

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers: [
        LoginComponent,
        { provide: RoutingService, useValue: MockRoutingService },
        { provide: AuthenticationService, useValue: MockAuthenticationService }
      ]
    })
    .compileComponents();
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
  });

也:

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers: [
        LoginComponent,
        { provide: RoutingService, useValue: MockRoutingService },
        { provide: AuthenticationService, useValue: MockAuthenticationService }
      ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

还有:

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers: [
        LoginComponent,
        { provide: RoutingService, useValue: MockRoutingService },
        { provide: AuthenticationService, useValue: MockAuthenticationService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

LoginComponent

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  private password = '';
  private email = '';
  private emailErr = '';
  private passwordErr = '';

  constructor(private authService: AuthenticationService, private routingService: RoutingService) { }

  ngOnInit() {
  }

  onSubmit() {
    this.emailErr = '';
    this.passwordErr = '';

    const response: { ['emailValid']: boolean, ['passwordValid']: boolean } = this.authService.login(this.email, this.password);

    const self = this;
    setTimeout(() => {
      if (response.emailValid === false) {
        self.emailErr = '* Your username was incorrect, please try again.';
        return;
      } else if (response.passwordValid === false) {
        self.passwordErr = '* Your password was incorrect, please try again.';
        return;
      }
      self.routingService.route('home');
    }, 300);
  }

  validateEmail() {
    this.emailErr = '';
    if (this.email === '') {
      this.emailErr = '* Please enter your email.';
    }
  }

  validatePassword() {
    this.passwordErr = '';
    if (this.password === '') {
      this.passwordErr = '* Please enter your password.';
    }
  }

  isValid() {
    if (this.password === '' || this.email === '') {
      return false;
    } else if (this.emailErr !== '' || this.passwordErr !== '') {
      return false;
    }
    return true;
  }

}

我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

正如nash11所指出的,您肯定需要从提供者列表中删除LoginComponent,并且第一个beforeEach应该运行async

我希望这样做实际上会得到不同的消息,告诉您ngModel不是<input/>的已知属性

有两种方法可以使测试正常工作,这取决于您是希望[{ngModel}]像通常那样工作,还是只希望对{{{ 1}}实际上有效。

因此,如果您希望ngModel能够正常工作,则需要将[{ngModel}]导入到TestBed中。

如果您不介意ngModel可以工作,而仅仅是存在的属性,则可以在TestBed内部设置FormsModule

NO_ERRORS_SCHEMA

这是工作中的stackblitz

答案 1 :(得分:0)

LoginComponent不是provider。将其添加到声明中就足够了。尝试从LoginComponent中删除providers,然后再次运行测试。

我会选择您的第三个选择。 async使得所有异步代码都可以在继续之前完成。

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers: [
        { provide: RoutingService, useValue: MockRoutingService },
        { provide: AuthenticationService, useValue: MockAuthenticationService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });