如何在jest中窥探相同的模块函数?

zed5wv10  于 2023-04-18  发布在  Jest
关注(0)|答案(2)|浏览(113)

我正在为一个函数编写单元测试,该函数调用同一模块中的另一个函数。

export function add(a, b) {
  return a + b
}

export function showMessage(a, b) {
  let sum = add(a, b)
  return `The sum is ${sum}`
}

测试:

import * as Logics from './logics;

describe('showMessage', () => {
  it('should return message with sum', () => {
      let addSpy = jest.spyOn(Logics, 'add')
      let  showMessageResponse = Logics.showMessage(2, 2)
      expect(addSpy).toHaveBeenCalledTimes(1)
  });
});

我想测试一下在执行showMessage的时候,add函数是否被调用。上面的一个给出了以下错误:
预期呼叫数:1接收的呼叫数:0
我找到了一个解决方案,但需要改变函数的导出方式:

function add(a, b) {
  return a + b
}

function showMessage(a, b) {
  const sum = Logics.add(a, b)
  return `The sum is ${sum}`
}

const Logics = {
  showMessage,
  add
}
export default Logics

我不想更改导出函数的方式。

mspsb9vt

mspsb9vt1#

简而言之,如果不改变导出,你就无法真正实现它。你可以阅读原因(也许还有其他选项on this answer以及这个答案)。
一个更好的选择imo会像这样(在你的logics.js文件中):

import * as Logics from './logics;

然后在showMessage函数中使用它,就像你在第二个例子中所做的那样:

const sum = Logics.add(a, b)

基本上,只需导入logics.js中的所有内容,并使用该值来获取对相同add函数的引用。
补充说明:虽然正确地模拟了add,但它与showMessage中调用的函数不同,基本上不能模拟该函数(您也可以检查此代码以获得证明

describe("showMessage", () => {
  it("should return the mocked sum (PASSES)", () => {
    jest.spyOn(Logics, "add").mockReturnValue(123);
    const showMessageResponse = Logics.add(2, 2);
    expect(showMessageResponse).toBe(123);
  });

  it("should return message with sum (FAILS)", () => {
    let addSpy = jest.spyOn(Logics, "add").mockReturnValue(123);
    const showMessageResponse = Logics.showMessage(2, 2);
    expect(addSpy).toHaveBeenCalledTimes(0);
    expect(showMessageResponse).toBe(`The sum is 123`);
  });
});

)还发布了in this sandbox

5cg8jx4n

5cg8jx4n2#

理想情况下,你应该独立于功能进行测试,一个测试不负责另一个功能的测试功能。
这不是最好的方法,但你可以这样做:
util.js

export function add(a, b) {
  return a + b;
}

export function showMessage(a, b, addNew = add) {
  let sum = addNew(a, b);
  return `The sum is ${sum}`;
}

在你的测试中,你可以这样做:util.test.js

import * as Logics from "./util";

describe("showMessage", () => {
  it("should return message with sum", () => {
    let addSpy = jest.spyOn(Logics, "add");
    addSpy.mockReturnValue(123);
    let showMessageResponse = Logics.showMessage(2, 2, addSpy);
    expect(addSpy).toHaveBeenCalledTimes(1);
    expect(showMessageResponse).toBe(`The sum is 123`);
  });
});

下面是你可以玩的沙盒:https://codesandbox.io/s/jest-test-forked-9zk1s4?file=/util.test.js:0-366

相关问题