Reputation: 7144
I'm learning writing unit test with Jest.
I use typescript, but it shouldn't be a problem here. Feel free to provide examples with pure JavaScript.
Until now I have function:
const space = String.fromCharCode(0x0020);
const rocket = String.fromCharCode(0xD83D, 0xDE80);
let notified: boolean = false;
export const logHiring = (message: string = "We're hiring!", emoji: string = rocket) => {
if (!notified) {
console.info(
[message, emoji]
.filter((e) => e)
.join(space)
);
notified = true;
}
};
Yes, function should log to console just one message per initialization.
And not really working tests:
import {logHiring} from "../index";
const rocket = String.fromCharCode(0xD83D, 0xDE80);
// First test
test("`logHiring` without arguments", () => {
let result = logHiring();
expect(result).toBe(`We're hiring! ${rocket}`);
});
// Second test
test("`logHiring` with custom message", () => {
let result = logHiring("We are looking for employees");
expect(result).toBe(`We are looking for employees ${rocket}`);
});
// Third test
test("`logHiring` multiple times without arguments", () => {
let result = logHiring();
result = logHiring();
result = logHiring();
expect(result).toBe(`We're hiring! ${rocket}`);
});
I have two problems:
spyOn
without succes.notified
variable for each test?Upvotes: 0
Views: 4236
Reputation: 4789
How can I test console logs? I've tried spyOn without succes.
https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname
const spy = jest.spyOn(console, 'log')
logHiring();
expect(spy).toHaveBeenCalledWith("We're hiring!")
How can I reset internal (from function) notified variable for each test?
export a getter/setter function like
// index.js
export const setNotified = (val) => { notified = val }
export const getNotified = _ => notified
// index.test.js
import { getNotified, setNotified } from '..'
let origNotified = getNotified()
beforeAll(_ => {
setNotified(/* some fake value here */)
...
}
afterAll(_ => {
setNotified(origNotified)
...
}
Upvotes: 1