Jest:在测试函数内使用的模拟对象

qmelpv7a  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(187)

我想模拟一个对象在被测试函数中使用。我发现我的另一张票是在被测试函数中调用函数,但是我需要替换那里使用的某个对象。在Jest中可能有这样的事情吗?

实用程序.测试.js

describe('testname', function () {
    it('import test', function () {
      Utils.generateRandomPoints(10); // inside this function, I'd like to mock used object
    });
});

实用程序.js

export function generateRandomPoints(arrayLength) {    
    const result = [];

    for (let i = 0; i < 100; i++) {
        // instead of "new Point" I'd like to use "new MockedPoint" for testing.
        result.push(new Point(i)); 
    }
    
    return result;
};
a7qyws3x

a7qyws3x1#

const MockPoint = jest.fn();
jest.mock('path/to/Point', () => ({
  Point: jest.fn().mockImplementation(MockPoint),
}));

并且您可以向MockPoint添加任何功能,例如

const MockPoint = jest.fn((props) => console.log(props));

相关问题