I am using Jasmine to write some test cases. It looks like this:
Class Definition:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return this.firstName + this.lastName;
}
getName () {
setTimeout(() => {
return this.getFullName();
}, 100)
}
}
module.exports = Person;
Test code:
const Person = require('./index');
describe('Test Person methods', () => {
beforeEach(() => {
programmer = new Person('John', 'Gray');
spyOn(programmer, 'getFullName');
programmer.getName();
});
it('getName should call getFullName', () => {
expect(programmer.getFullName).toHaveBeenCalled();
})
});
getName is an async function which calls getFullName after some time. Because of this async nature, the it spec executes immediately after getName is called, and so the test fails.
I know that I can use done function of Jasmine to carry out async testing, but I am not sure how to implement it here? In the docs, the done method is called from within the async code only, but that code is not accessible to the test as its handled internally by getName method.
Or is there any other approach which does not use done method?
Here is a working sample of this code.