Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a function called another function in Jasmine test

Consider the following Jasmine code I am running through Karma:

class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    getName() { this.getFullName() }
    getFullName() { this.firstName + this.lastName }
}

describe('Test Person', () => {

    beforeEach(() => {
        const programmer = new Person('John', 'Gray');
        spyOn(programmer, 'getFullName');
        programmer.getName();
    });

    it('getName should call getFullName', () => {
        expect(programmer.getFullName).toHaveBeenCalled();
    })
});

I want to check that programmer.getName did actually call programmer.getFullName. I know this can be tested here by checking the return value of getName, but I want to explicitly check if getFullName was called as this is the scenario in the actual code I am working with. I have implemented my code like shown above, but it's not working. Where am I going wrong?

I checked this post, but it's not working here.

like image 610
darKnight Avatar asked Apr 05 '18 15:04

darKnight


1 Answers

Move the programmer variable above in the describe block. Also, I suggest calling getName() it the test iteslf. This should work:

let programmer;
beforeEach(() => {
    programmer = new Person('John', 'Gray');
    spyOn(programmer, 'getFullName');
});

it('getName should call getFullName', () => {
    programmer.getName();
    expect(programmer.getFullName).toHaveBeenCalled();
})
like image 114
Dušan Stanković Avatar answered Sep 30 '22 06:09

Dušan Stanković