jest如何测试同一模块内的函数依赖?

比如util.js,定义了两个函数:

const util = {
  A() {
    return this.B();
  },
  B() {
    return 'B';
  }
};
module.exports = util;

那么,怎么测试函数A?

test("A=>B,case:1", () => {
  let A = util.A;
  expect(A()).toBe("B");
});

这么写测试会报错:TypeError: this.B is not a function。难道要用mock不成?

阅读 8.5k
1 个回答

你这个的问题是因为 this 指向变了的问题,跟单测无关。

你把你这代码直接运行,它也是不能跑的:

const util = {
    A() {
        return this.B();
    },
    B() {
        return 'B';
    },
};

let A = util.A;
A();      // ERROR! this.B is not a function

util.A(); // 'B'
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题