Jest.js 嘲笑笑话后恢复实现

zzoitvuj  于 2023-09-28  发布在  Jest
关注(0)|答案(2)|浏览(142)

我试着模拟一个函数,并在测试后使用真实的的实现进行其他测试。

const myService = () => {
    return {
      foo: () => return 1;
    }
}
const myService = require('./myService.js');

jest.mock('./myService');

describe('testing myService', () => {
  it('should return 2 by mocked', () => {
    myService.mockImplementation(() => ({
      foo: jest.fn().mockResolvedValueOnce(2),
    }));
    expect.assertions(1);
    expect(myService().foo()).toBe(2);
    jest.restoreAllMocks();
  });
  it('should return 1', () => {
    expect(myService().foo()).toBe(1);
  });
});

但在此之后,foo()仍然被嘲笑。

ukqbszuj

ukqbszuj1#

spyOn(object,methodName)是为对象创建模拟方法更好的选择。
我们可以通过在afterEach()钩子中使用jest.restoreAllMocks()将方法恢复到原始实现。
请注意,jest.restoreAllMocks()仅在使用jest.spyOn创建mock时才有效;其他模拟将需要您手动还原它们。
例如
myService.js

const myService = () => {
  return {
    foo: () => 1,
  };
};
module.exports = myService;

myService.test.js

const myService = require('./myService.js');

describe('testing myService', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should return 2 by mocked', () => {
    const service = myService();
    jest.spyOn(service, 'foo').mockReturnValueOnce(2);
    expect(service.foo()).toBe(2);
    expect(service.foo).toBeCalledTimes(1);
  });
  it('should return 1', () => {
    const service = myService();
    expect(jest.isMockFunction(service.foo)).toBeFalsy();
    expect(service.foo()).toBe(1);
  });
});

测试结果:

PASS  examples/68459394/myService.test.js (8.465 s)
  testing myService
    ✓ should return 2 by mocked (3 ms)
    ✓ should return 1

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.548 s
bvpmtnay

bvpmtnay2#

如果你想在Jest中创建一个mock函数,同时保留对原始实现的引用,你可以使用下面的实用函数:

/**
 * Creates a mock function and attaches the original implementation to the mock object.
 *
 * @param {Function} fn - The original function to be mocked.
 * @returns {Function} A Jest mock function with the original implementation attached.
 */
const createMock = (fn) => {
    const mockFn = jest.fn();
    mockFn.mock.original = fn;
    return mockFn;
};

使用示例:
假设你有一个db.js模块,它有两个函数,getOrder和updateOrder:

// db.js
const getOrder = (orderId) => {
    return { id: orderId, price: 100 };
};

const updateOrder = (order) => {
    console.log('order updated successfully!');
    return order;
};

module.exports = {
    getOrder,
    updateOrder,
};

要模拟getOrder函数并在以后恢复它,可以执行以下操作:

// Mock the getOrder function
db.getOrder = createMock(db.getOrder).mockReturnValue({
    id: 1,
    price: 20,
});

// ... Perform your tests using the mocked function ...

// Restore the original implementation
db.getOrder = db.getOrder.mock.original;

相关问题