ฉันกำลังทดสอบฟังก์ชันที่เรียกใช้ฟังก์ชันอื่นที่นำเข้าจาก anotherFile
outsideFunc
นั้นส่งคืนวัตถุที่มี 'ชื่อ' ฉันจำเป็นต้องมีสิ่งนี้เพื่อที่จะผ่านการทดสอบที่เหลือ/ฟังก์ชันทำงานได้อย่างถูกต้อง
systemUnderTest.js
import { outsideFunc } from './anotherFile.js';
function myFunc() {
const name = outsideFunc().name;
}
anotherFile.js:
export function outsideFunc() {
return { name : bob }
}
ฉันไม่สนใจการทดสอบ anotherFile
หรือผลลัพธ์ของ outsideFunc
แต่ฉันยังต้องส่งคืนค่าจำลองซึ่งเป็นส่วนหนึ่งของการทดสอบ myFunc
systemUnderTest.spec.js
describe("A situation", () => {
jest.mock("./anotherFile", () => ({
outsideFunc: jest.fn().mockReturnValue({
name: 'alice'
})
}));
it("Should continue through the function steps with no problems", () => {
expect(excludeCurrentProduct(initialState)).toBe('whatever Im testing');
});
});
ปัญหาที่ฉันได้รับคือ เมื่อการทดสอบหน่วยทำงานจนถึง myFunc
const name
จะส่งคืน undefined
โดยที่ควรจะส่งคืน alice
ฉันคาดหวังว่าจะได้รับข้อมูลจาก jest.mock
ของไฟล์ anotherFile
ของฉันและฟังก์ชันจำลองการส่งออก แต่ไม่ได้รับการตอบสนองที่ถูกต้อง
เมื่อฉันสินทรัพย์ที่ฉันคาดหวัง name = alice
ฉันจะได้รับ name = undefined
จริงๆ