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();
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With