I have a function that runs asynchronously, console logging the numbers 1 through 5 in order after a random setTimeout. I want to write a test for this function using Jest. How do I write one that tests that the console.log is 1, 2, 3, 4, 5 ?
Jest by default prints all console. log (warnings, errors, etc) messages to the console. That's great - it helps you understand what's going on in your code when tests run.
Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly.
- [Instructor] The Jest framework can be used to functionally test an application. The results can be included in a code coverage report, which is really useful. As a reminder, functional testing literally tests the functionality of an application.
In order to run a specific test, you'll need to use the jest command. npm test will not work. To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli . Then simply run your specific test with jest bar.
Yes you can using jest.fn
.
Here is an example:
File hello.js
console.log("Hello World");
File hello.test.js
let outputData = "";
storeLog = inputs => (outputData += inputs);
test("console log Hello World", () => {
console["log"] = jest.fn(storeLog);
require("./hello.js");
expect(outputData).toBe("Hello World");
});
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