尝试用玩笑模拟函数,但玩笑调用原始函数

问题描述 投票:0回答:1

由于我对单元测试相对较新,因此我的主要目标是采用函数模拟,特别是针对“add()”函数。但我在实现这个目标的过程中遇到了困难。

// math.js
export const add = (a, b) => {
    console.log("Original implementation");
    return a + b;
}

// myModule.js
import { add } from './math';

export const multiplyAndAdd = (a, b, c) => {
  const result = add(a, b);
  return result * c;
};


// myModule.test.js
import { jest } from '@jest/globals';
import * as math from '../math';
import { multiplyAndAdd } from '../myModule';

// Mock the 'add' function
jest.mock('../math', () => ({
  ...jest.requireActual('../math'), // Use the actual implementation
  add: jest.fn(),
}));

describe('multiplyAndAdd', () => {
  it('multiplies and adds using the original add function', () => {
        // Set up the mock implementation for 'add'
        math.add.mockImplementation((a, b) => {
        console.log("Fake calling...);
        return a + b;
    });

    // Call the function you want to test
    const result = multiplyAndAdd(2, 3, 4);

    // Assert the result
    expect(result).toBe(20);
  });
});

错误:

类型错误:math.add.mockImplementation 不是函数

javascript node.js unit-testing jestjs
1个回答
0
投票

您可以尝试以下替代方案:

import * as math from '../math';

beforeEach(() => {
  // Spy on and mock only the add method
  jest.spyOn(math, 'add').mockImplementation((a, b) => a + b);
});

afterEach(() => {
  // Restore the original implementation after each test if needed
  jest.restoreAllMocks();
});

如果您想模拟对象或模块导出的特定方法,同时保留对象原始实现的其余部分,您可以使用 jest.spyOn()。

这种方法允许您模拟单个函数,而不影响模块导出的其余部分,从而对模拟的内容提供更精细的控制。

© www.soinside.com 2019 - 2024. All rights reserved.