#New to Unit Tests (JasmineKarma) - How to test a simple get Method?

10 messages · Page 1 of 1 (latest)

cosmic dirge
#

In one of my components I have this simple getMethod, in which I ask my service, which works with LocalStorage, to put the data it has into my array.

getEintraege(): void {
this.eintraege = JSON.parse(this.eintragService.getData('token')!) || []
}

All I could understand is that I start the test-Method like this:

it('should display eintraege or none')

Could you help me with the methods I could use to test, if my array this.eintraege is empty or has items in it?

frozen pond
#

g!codeblock @cosmic dirge

civic creekBOT
#

@cosmic dirge, you can use the following snippet to have your code formatted and colored by Discord. Replace ts with the language you need (i.e. html, js, css, etc)
```ts
// your code goes here
```

frozen pond
#

getEintraege is kind of a weird method to begin with. I wouldn't have it in my code. And it probably should be a private method so not something unit tested.

#
it('should display einteraege', (): void => {
  expect(comonent.eintraege).withContext('eintraege').toEqual(expectedEintraege);
});

No knowing what eintraege is, nor how it is set, nor what it is used for I cannot really suggest anything good.

cosmic dirge
#

eintraege is an interface with the following attributes:

export interface Eintrag {
  beschreibung: string;
  erledigt: boolean;
  faelligkeitsdatum: string;
}

I created this mockEintraege, so I can use it for my test

import {Eintrag} from "../interfaces/eintrag";

// Fuer Tests, muss mithilfe von Spys zur Verfügung gestellt werden
export const mockEintraege: Eintrag[] = [
  { beschreibung: 'Essen', erledigt: false, faelligkeitsdatum: '15.09.2022' },
  { beschreibung: 'Schlafen', erledigt: true, faelligkeitsdatum: '15.09.2022' },
  { beschreibung: 'Zähne putzen', erledigt: false, faelligkeitsdatum: '15.09.2022' }
];

I'm struggling to import the mock and initialize it into a variable inside my component.spec.ts

I also tried creating a SpyObj with my Service, which works with the LocalStorage, but I didn't succed there as well

frozen pond
#

Show more code

cosmic dirge
#
export class EintraegeComponent implements OnInit {

  // Deklariere 'eintrag', um ihn zu löschen oder seinen Status zukünftig zu ändern
  eintrag!: Eintrag;

  // Array fuer alle Eintraege
  eintraege: Eintrag[] = [];


  constructor(private eintragService: EintragService ) { }

  // Aufruf der Methode, nachdem EintraegeComponent erstellt wurde
  ngOnInit(): void {
    this.getEintraege();
  }

  // Zuweisung aller Eintraege in das 'eintrage-Array'
    getEintraege(): void {
      this.eintraege = JSON.parse(this.eintragService.getData('token')!) || []
    }
#
// Speichert Daten, löscht Daten und fügt neue Daten in das LocalStorage hinzu
export class EintragService {

  constructor() { }

  // Speichere Wert mit Schlüssel "token" im Localstorage ab
  public saveData(key: string, value: string) {
    localStorage.setItem('token', value);
  }

  // Erhalte mit spezifischem Schlüssel gespeicherte Daten
  public getData(key: string) {
    return localStorage.getItem(key)
  }

}
#

and my spec.ts of eintrag-component

describe('EintraegeComponent', () => {
  let component: EintraegeComponent;
  let fixture: ComponentFixture<EintraegeComponent>;
  let eintraege: Eintrag[] = [];
  let service: EintragService;
  beforeEach(async () => {
    const eintragSericeSpy = jasmine.createSpyObj<EintragService>(['getData']);
    // @ts-ignore
    eintragSericeSpy.getData.and.callFake(function () {
      return of({
        results: [{
          beschreibung: 'Schlafen',
          erledigt: true,
          faelligkeitsdatum: '01.01.2022'
        }]
      })
    });
    await TestBed.configureTestingModule({
      imports: [MatChipsModule,
        MatFormFieldModule, NoopAnimationsModule
      ],
      declarations: [ EintraegeComponent ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [{provide: EintragService, useValue: eintragSericeSpy}]
  },)
    .compileComponents();
    service = TestBed.inject(EintragService);
    fixture = TestBed.createComponent(EintraegeComponent);
    // eintraege = TestBed.createComponent(mockEintraege);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should return eintraege or none', () => {

  })

});