1
votes

I have a component. It takes a value as its @Input. If the onDelete() method is called, there is an EventEmitter that will emit the value that was put in. I am trying to write a test for this component, and the value I get from the emitter is undefined, not the value I passed.

Here is the test:

import { CheckedComponent } from '../checked/checked.component'; 

describe('CheckedComponent', () => {
    it('emits the input value on delte', () => {
        let total = null; 
        const component = new CheckedComponent(); 
        component.item = 'example'; 
        component.delete.subscribe(item => {
            total = item; 
        });
        component.onDelete()
        console.log("HERE", total)
        expect(total).not.toBeNull();
        // expect(total).toEqual('example'); 
    }); 
});  

The commented line does not work. total equals "undefined," not 'example.' Interestingly, if I console.log(component.item), I still get the 'example' piece of data.

Here is the actual component:

import { Component, Input, Output, EventEmitter } from '@angular/core'; 

@Component({
    templateUrl: './checked.component.html', 
    selector: 'checked', 
    styleUrls: ['./checked.component.css']
})

export class CheckedComponent {
    @Input('item') item; 
    @Output() delete = new EventEmitter()

    onDelete() {
        this.delete.emit(this.item.value)
    }
}

Not sure what I am doing wrong here. Semi-new to testing in Angular 4. Any guidance would be appreciated. Thanks!

2
I love people who downvote questions for completely arbitrary reasons. It makes stackoverflow a really pleasant place to seek help. Was my question unreasonable? No, it wasn't. - J Seabolt
I just upvoted. I don't see why this isn't a good question. - Wim Bokkers

2 Answers

0
votes

As you are emitting this.delete.emit(this.item.value), you need to assign proper value to the item in unit tests. Update your unit test code as below.

const component = new CheckedComponent(); 
component.item =  { value : 'example'}; 

You should expect values in the subscribe method. Because the value of "total" might be assigned with value of "item" later time.

import { CheckedComponent } from '../checked/checked.component'; 
describe('CheckedComponent', () => {
  it('emits the input value on delte', () => {
    let value = null; 
    const component = new CheckedComponent(); 
    component.item =  { value : 'example'}; 
    component.delete.subscribe(item => {
        value= item; 
        console.log("HERE", total)
        expect(value).not.toBeNull();
        expect(value).toEqual('example');
    });
    component.onDelete()
  }); 
});
0
votes

The problem was the component expected an object with a VALUE, not a pure value. This fixed it:

component.item = {value: 'example'};