'Jest pass in one file, but fail in other file
I have a very simple js-program in a file called Task2.js, where one function processInput(date)
is used to process the user input. I have written some basic tests for it, but most of them failed with unexpected messages. I wrote all those tests in the file Task2.test.js. When I move the tests that fail from Task2.test.js to Task2.js and run jest again, all of them pass. I have no idea why they work in one file, but not the other.
Task2.js:
function processInput(date){
if(date.trim() == "quit"){
rl.close();
throw new Error("User requested quit");
}
// Trim trailing spaces and then split into three variables
try{
// Regex that matches any year starting with 1-9, any month between 1-12, and any day between 1-31
if(!(/^\s*[1-9]\d*\s+([1-9]|1[0-2])\s+([1-9]|[1-2][0-9]|3[01])\s*$/.test(date))){
console.log("Invalid input, please try again");
return false;
};
[y, m, d] = date.trim().split(/\s+/);
} catch(error){
console.log("Invalid input, please try again");
return false;
}
return [y, m, d];
}
Some tests in Task2.test.js:
const processInput = require("./Task2");
test("TestQuit", () => {
expect(() => processInput("quit")).toThrow();
});
test("TestInvalidInput", () => {
expect(processInput(" 2021 13 13 ")).toBeFalsy();
});
Here's what those tests return when run in Task2.test.js:
TestQuit
expect(received).toThrow()
Received function did not throw
TestInvalidInput
expect(received).toBeFalsy()
Received: " 2021 13 13 undefined NaN"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|