简体   繁体   中英

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.

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();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM