Explore essential concepts for creating, structuring, and executing your first test using the Jest testing framework. This quiz covers syntax, configuration, and best practices for new users aiming to verify JavaScript code with Jest.
Which of the following shows the correct basic syntax for writing a test case in Jest to check if a function 'add' returns 5 when given 2 and 3?
Explanation: The correct syntax uses the 'test' function with a string description and a callback containing an 'expect' statement with 'toBe' for exact value checking. 'check' and 'equals' are not valid Jest keywords, making option B incorrect. Option C incorrectly uses '==' instead of 'toBe', and omits braces for clarity. Option D incorrectly places arguments in the test call and misuses 'describe' syntax. Only option A demonstrates the correct structure.
According to common conventions in Jest, which file name is most likely to be automatically recognized as a test file?
Explanation: Jest automatically detects files with '.test.js' as test files. 'test-mathfile.js' does not match the convention, so it is not automatically picked up. 'mathSpec.js' uses a different naming scheme not recognized by default, and 'maths-checklist.js' is a generic name rather than a test identifier. This makes 'math.test.js' the most appropriate for automatic recognition.
If you have installed Jest locally, which command would you typically run in the terminal to execute your tests?
Explanation: Using 'npx jest' invokes the local Jest executable directly, which is the common method to run all tests. 'run jest' and 'jest-start' are not standard commands in this context. 'npm run unit' would only work if a script named 'unit' is defined in your configuration, which is not the default. 'npx jest' ensures Jest is located and executed properly.
When writing your first expectation in Jest, what is the purpose of using the 'expect' function?
Explanation: The 'expect' function is used to define the value you are checking, so it serves as the basis for each assertion in your test. It does not initialize test files (B), run the main application code (C), or specifically handle asynchronous logic (D)—though it can be used in async tests. The primary goal is to specify and verify expected outcomes.
In a simple Jest test, which element should directly describe the behavior or outcome you are testing?
Explanation: The first argument of the 'test' function is a descriptive string explaining what is being tested, making your test readable and maintainable. The file name provides context but doesn't specify individual test behavior. Comments can help but are not part of Jest's reporting system. The callback function holds the code to execute the test, not the description.