茉莉花测试:预期未定义等于对象。 (如何测试@input)

时间:2019-11-18 08:38:41

标签: angular typescript karma-jasmine

我对此错误感到烦恼。我想我忘记了什么,无法弄清楚是什么。 任务很简单:只需测试我的简单组件即可。 我们开始:

import { Component, OnInit, Input } from '@angular/core';
import { ButtonModel } from './model/button.model';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() public button: ButtonModel;

  constructor() { }

  public ngOnInit(): void {
  }

  public getClasses(): [string, string] {
    return [
      this.button.Size,
      this.button.Color
    ];
  }
}

并进行测试:

import { Spectator, createHostFactory } from '@ngneat/spectator';
import { RouterTestingModule } from '@angular/router/testing';
import { ButtonComponent } from './button.component';
import { MockComponent } from 'ng-mocks';


describe('[ButtonComponent]', () => {
  let spectator: Spectator<ButtonComponent>;
  const createHost = createHostFactory({
    component: MockComponent(ButtonComponent),
    imports: [RouterTestingModule]
  });

  beforeEach(() => {
    spectator = createHost('<app-button></app-button>');
  });

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

  it('should get default classes', () => {
    expect(spectator.component.getClasses()).toEqual(['big', 'primary-theme-color']);
  });
});

和HTML:

<button [ngClass]="getClasses()">
  {{button.Text}}
</button>

那个错误:

  

未定义的期望值等于['big','primary-theme-color']。错误:   预期的undefined等于['big','primary-theme-color']。       在       在UserContext上。 (http://localhost:9876/_karma_webpack_/src/app/shared/components/button/button.component.spec.ts:24:46)       在ZoneDelegate.invoke(http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)       在ProxyZoneSpec.onInvoke(http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1

2 个答案:

答案 0 :(得分:1)

您正在使用旁观者进行测试,可以阅读该工具的文档:https://github.com/ngneat/spectator

在您的情况下,您的spectator.setInput('button', {Text: 'my text', Size: '...', Color: '...'})前应该是expect

答案 1 :(得分:0)

在没有主机组件的情况下进行测试并设置按钮属性值对我来说有用

  let spectator: Spectator<ButtonComponent>;   
  const createComponent = createComponentFactory(ButtonComponent);

  beforeEach(() => {
    spectator = createComponent({
      props: {
        button: {Size: "big", Color: 'primary-theme-color'}
      }
    });
  });

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

  it('should get default classes', () => {
    expect(spectator.component.getClasses()).toEqual(['big', 'primary-theme-color']);
  });