How can I use jasmine.js to test for console output?
There are a couple of things that are wrong with your code above. As pointed out, having multiple return statement will not work. Also, when defining a new object, it is preferable to use the object literal syntax over using new Object
.
What you would normally do is something more like this:
var function_to_test = function () {
var person = {
name : "Nicholas",
age : 29
};
return person;
};
Using the function above, there are a couple of ways you could test this. One it to mock out the console.log object using Jasmine Spies.
it("should test for the function_to_test's console output", function () {
console.log = jasmine.createSpy("log");
var person = function_to_test();
expect(console.log).toHaveBeenCalledWith(person);
});
The other is to test the actual output of the function.
it("should return a person", function () {
var person = function_to_test();
expect(person).toEqual({ name : "Nicholas", age : 29 });
});
I know this is an old question (7+ years old) but I just came upon this answer today through Google search. From this answer, I changed it to the following and has worked for me.
spyOn(console, 'error');
const dto = new DTO(); // add to console.error if no parameter is given
expect(console.error).toHaveBeenCalled();