Jest - 模拟工厂函数

Roo*_*ode 4 javascript jestjs

我想测试的功能是createCarAndDrive()哪个使用Car模块。我想模拟Car模块中的一个函数,以便不调用其实际函数,而是调用模拟函数。

因此,该Car函数返回两个函数gas()brake()Car使用工厂函数模式来实现。所以这两个函数被包装起来Car并且在被调用之前不会被公开Car

是否可以以某种方式模拟brake()要返回的函数false

这是实现。

// Car.js
function Car({ name, model }) {
  function gas(speed) {
    return `${name} ${model} goes forward at a speed of ${speed}km/h`;
  }
  function brake() {
    return true;
  }

  return {
    gas,
    brake,
  };
}

// driver.js
function createCarAndDrive() {
  const car = Car({ name: 'Fiat', model: 'Punto' });
  car.gas(123);
  return car.brake();
}

// driver.test.js
describe('drive', () => {
  beforeEach(() => {
    // How to mock function inside a function?
    jest.mock('./Car', () => ({
      brake: jest.fn().mockImplementation(() => false),
    }));
  });

  test('it should not brake', () => {
    const itHitBreak = createCarAndDrive();
    expect(itHitBreak).toBe(false);
  });
});
Run Code Online (Sandbox Code Playgroud)

Bri*_*ams 7

jest.mock工厂函数在测试函数中不起作用

移至jest.mock测试的顶层范围,它应该可以工作:

import { createCarAndDrive } from './driver';

jest.mock('./Car', () => ({
  Car: () => ({
    gas: () => 'mock gas',
    brake: () => false
  })
}));

describe('drive', () => {
  test('it should not brake', () => {
    const itHitBreak = createCarAndDrive();
    expect(itHitBreak).toBe(false);  // Success!
  });
});
Run Code Online (Sandbox Code Playgroud)