Reputation: 75
I have a function that prints a string
I want to test that function actually prints the string provided
The way I understand this should work is: 1. store the log in a var 2. assert content stored in the var is toBe what I expect
const log = 'hello2';
let myFunction = (log) => {
console.log(log);
};
myFunction(log);
const {myFunction} = require('../function-conversion');
test('Function prints message: "hello"', () => {
expect(myFunction(log).toBe(console.log("hello")))
});
Function prints message: "hello" (1ms)
Function prints message: "hello"
ReferenceError: log is not defined
at Object.log (tests/function-conversion.test.js:4:20)
console.log ../function-conversion.js:11 hello2
Upvotes: 1
Views: 3419
Reputation: 75
I pumped up the initial function a bit. In case one should test a console.log message, he should push the string to an array.
let arrayOfMessages = [];
let functionThatPrintsTheArrayOfMessages = () => {
// pushing the messages to the array can be done when invoking the function as in line 19
// console.log(message.push('hello','hi'));
for (let i in arrayOfMessages){
console.log(arrayOfMessages[i])
};
return arrayOfMessages;
};
functionThatPrintsTheArrayOfMessages(arrayOfMessages.push('hello', 'hi'));
This is the jest test.
test('Function prints message: "hello", "hi"', () => {
expect(functionThatPrintsTheArrayOfMessages()).toContain('hello')
expect(functionThatPrintsTheArrayOfMessages()).toContain('hi')
expect(functionThatPrintsTheArrayOfMessages()).toEqual(['hello', 'hi'])
});
I would like to know if this is correct and other ways of testing. Involving Jest.
Upvotes: 1
Reputation: 4200
There is an error to below line:
expect(myFunction(log).toBe(console.log("hello")))
While calling function myFunction(log)
you should pass any string instead of log variable which is not declared anywhere (into function-conversion.test.js
file) like "hello"
.
I don't have an environment up so couldn't test. But what you can do is:
describe('SearchResultsComponent', () => {
let spy;
let myFunction = (log) => {
console.log(log);
};
myFunction(log);
beforeAll(async () => {
spy = jest.fn();
});
test('Function prints message: "hello"', () => {
const log = 'hello';
spy = jest.spyOn(console, 'log');
myFunction(log);
expect(spy).toHaveBeenCalled();
expect(spy.calls.argsFor(0)).toEqual(['hello']);
});
});
Upvotes: 1