0
votes

I have troubles with that error. I think i forgot something and cant figure out what is it. The task is simple: just test my simple component. Here we go:

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

And tests:

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

And HTML:

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

And that error:

Expected undefined to equal [ 'big', 'primary-theme-color' ]. Error: Expected undefined to equal [ 'big', 'primary-theme-color' ]. at at UserContext. (http://localhost:9876/_karma_webpack_/src/app/shared/components/button/button.component.spec.ts:24:46) at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1) at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1)

2

2 Answers

1
votes

You are using spectator for test, you can read the documentation of the tool: https://github.com/ngneat/spectator

In your case, it would be spectator.setInput('button', {Text: 'my text', Size: '...', Color: '...'}) before your expect

0
votes

Testing without host component and setting button property value worked for me,

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