How do I test JavaScript code with Jest?
Asked on Sep 10, 2024
Answer
Jest is a popular testing framework for JavaScript, especially for applications built with React. It allows you to write tests with an easy-to-use API.
<!-- BEGIN COPY / PASTE -->
// Example function to test
function add(a, b) {
return a + b;
}
// Jest test case
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
<!-- END COPY / PASTE -->
Additional Comment:
- Install Jest using npm with the command: "npm install --save-dev jest".
- Create a JavaScript file with the function you want to test, e.g., "add.js".
- Create a test file, e.g., "add.test.js", and include the test code as shown above.
- Run your tests using the command: "npx jest".
- Jest automatically finds files with ".test.js" or ".spec.js" extensions.
- Use "expect" to define assertions and "toBe" to check for equality.
Recommended Links:
← Back to All Questions