【问题标题】:Is there a way to access this (current instance) from within jest spyOn mockImplementation?有没有办法从 jest spyOn mockImplementation 中访问这个(当前实例)?
【发布时间】:2022-01-22 02:03:52
【问题描述】:

在我的测试套件中,我做了以下模拟类方法:

beforeEach(() => {
    jest
      .spyOn(MyClass.prototype, "loadVars")
      .mockImplementation(async () => {

        const file:string = `MyClass.${
          this.prefix  // <---- how can I address this?
        }.data.mock.json`;
        logger.info(`Mocking all parameters from ${file}`);

        return JSON.parse(
          fs.readFileSync(
            process.cwd() + `/../data/${file}`,
            "utf-8"
          )
        );
      });
  });

有没有办法从这个模拟中引用当前类实例?

【问题讨论】:

    标签: typescript jestjs mocking


    【解决方案1】:

    箭头函数() =&gt; {} 从其声明范围中捕获this 的值。所以要替换原型方法,需要使用function 语句。

    此外,Typescript 需要在此处提示 this 的预期值,因此您可以为 this 设置类型。

    我认为这应该符合您的期望:

    jest
      .spyOn(MyClass.prototype, 'loadVars')
      .mockImplementation(function (this: MyClass) {
        console.log(this.prefix) // works
      })
    

    【讨论】:

    • 是的。因此,我尝试切换到 std func 声明。我没有尝试的,如果可以注入这个:MyClass。谢谢亚历克斯!
    • 还有一点,是否有一些地方记录了这一点?我认为我可以将当​​前方法“loadVars”参数作为 func 回调的参数传递。他们将如何适应“this:MyClass”?
    • 文档:Declaring this in a Function。但是你可以在那之后添加 args。例如:(this: MyClass, firstArg: number) =&gt; void
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多