จำลองการนำเข้าจากไฟล์อื่น แต่ยังคงส่งคืนค่าจำลอง

ฉันกำลังทดสอบฟังก์ชันที่เรียกใช้ฟังก์ชันอื่นที่นำเข้าจาก 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 จริงๆ


person user1486133    schedule 16.10.2019    source แหล่งที่มา


คำตอบ (1)


systemUnderTest.js

import { outsideFunc } from './anotherFile.js';

// let's say that the function is exported
export function myFunc() {
   const name = outsideFunc().name;
   // and let's say that the function returns the name
   return name;
}

คุณสามารถอธิบายได้ในของคุณ

systemUnderTest.spec.js

import { myFunc } from './systemUnderTest';
import { outsideFunc } from './anotherFile';

// using auto-mocking has multiple advantages
// for example if the outsideFunc is deleted the test will fail
jest.mock('./anotherFile');


describe('myFunc', () => {
  describe('if outsideFunc returns lemons', () => {
    outsideFunc.mockReturnValue({name: 'lemons'});
    it('should return lemons as well', () => {
      expect(myFunc()).toEqual('lemons');
    });
  });
});

ตัวอย่างการทำงาน

person Teneff    schedule 16.10.2019