Check out the complete minimal reproducible example
Let's take a look at the app below:
src/food.js
const Food = {
carbs: "rice",
veg: "green beans",
type: "dinner"
};
export default Food;
src/food.js
import Food from "./food";
function formatMeal() {
const { carbs, veg, type } = Food;
if (type === "dinner") {
return `Good evening. Dinner consists of ${veg} and ${carbs}. Delicious!`;
} else if (type === "breakfast") {
return `Good morning. Breakfast includes ${veg} and ${carbs}. Yum!`;
} else {
return "No meal for you!";
}
}
export default function getMeal() {
const meal = formatMeal();
return meal;
}
Below is a test scenario I have set up:
tests_/meal_test.js
import getMeal from "../src/meal";
describe("meal tests", () => {
beforeEach(() => {
jest.resetModules();
});
it("should display dinner", () => {
expect(getMeal()).toBe(
"Good evening. Dinner consists of green beans and rice. Delicious!"
);
});
it("should display breakfast (mocked)", () => {
jest.doMock("../src/food", () => ({
type: "breakfast",
veg: "avocado",
carbs: "toast"
}));
// prints out the newly mocked food!
console.log(require("../src/food"));
// ...however, we did not mock it in time, so this fails!
expect(getMeal()).toBe("Good morning. Breakfast includes avocado and toast. Yum!");
});
});
How can I effectively mock the Food
object for each individual test? Essentially, I want the mock to only apply to the "should display breakfast (mocked)" test case.
I also prefer not to alter the application source code if possible (although considering having Food
as a function that returns an object might be acceptable - still struggling to make that work as well)
Some methods I have attempted already:
- Passing the
Food
object throughgetMeal
+ employing dependency injection intoformatMeal
- (the main objective here is to avoid passing around
Food
throughout the entire app)
- (the main objective here is to avoid passing around
- Manual mocking +
jest.mock()
- there might be a solution within this approach, but managing the value and resetting it per test due to import time discrepancies has proven challenging- Using
jest.mock()
at the start could override it for every test case, and figuring out how to adjust or reset the value ofFood
for each test remains elusive.
- Using