【问题标题】:How to preserve "this" within Typescript Mocha test hooks如何在 Typescript Mocha 测试挂钩中保留“this”
【发布时间】:2021-10-15 22:54:58
【问题描述】:

在下面的示例中,token.test.ts 将测试夹具加载到 beforeEach 内的 this.token 中,以便在 token.behavior.ts 中的挂钩中重用。

// token.test.ts
import { shouldBehaveLikeToken } from './token.behavior';

describe("TokenTest", function () {
  beforeEach('reload token fixture', async function () {
    ({ token: this.token }) = await loadFixture();
  });

  shouldBehaveLikeToken();
  // More behavioral test suites
});
// token.behavior.ts
export function shouldBehaveLikeToken(): void {
  describe('balanceOf', function () {
    it('returns the correct balance', async function() {
      expect(await this.token.balanceOf(ADDRESS).to.equal(2)); // WORKS!
    });

  });

  function balanceOf() {
    return this.token.balanceOf(ADDRESS); // DOES NOT COMPILE WITH THIS FUNCTION!
  }
  
}

不管this.token 上的嵌套断言有多深,我都可以在 Mocha 挂钩(describe()/it())中访问this.token

但是,如果我创建一个使用 this.token 的帮助函数来使测试在测试套件中更加可组合,我会得到 'this' implicitly has type 'any' because it does not have a type annotationAn outer value of 'this' is shadowed by this container 的错误。不管它是否是箭头函数,也不管函数是在哪里定义的,都会发生这种情况。

有人可以解释发生了什么吗?如何创建一个使用 beforeEach 块中保留的 this 的辅助函数?

【问题讨论】:

    标签: javascript typescript mocha.js


    【解决方案1】:

    看起来您的外部函数 balanceOf 要求 this 上下文是 Mocha.Context 的上下文,这仅在 Mocha 测试中可用。您必须指定 balanceOf 函数的 this 类型,然后将函数显式绑定到 Mocha.Context 上下文,如下所示:

    export function shouldBehaveLikeToken(): void {
      describe('balanceOf', function () {
        it('returns the correct balance', async function() {
          // It is only within this callback that your `this` context is `Mocha.Context`.
          // The context will not carry over outside of the callback.
    
          expect(await balanceOf.bind(this)().to.equal(2)); // Bind the function here.
        });
      });
    
      function balanceOf(this: Mocha.Context) { // explicit `this` type here.
        return this.token.balanceOf(ADDRESS);
      }
    }
    

    您的第一个balanceOf 函数无法正确键入this 的原因是因为所有函数声明(使用function 关键字创建的函数)默认绑定windowglobal,或绑定到@987654334 @如果您处于严格模式。您可以阅读有关函数如何绑定其this 上下文here 的更多信息。

    【讨论】:

    • 谢谢!有什么方法可以将Mocha.Context 绑定到所有子函数,而不必为每个函数显式绑定?
    • 我不知道,但是您可以通过使用箭头函数在 Mocha 测试回调中编写函数来节省一些精力,例如const balanceOf = () => { /* ... */ } 或作为普通函数声明,对 bind 进行悬空调用,例如function balanceOf(this: Mocha.Context) { /* ... */ }.bind(this)。不过,您必须在 Mocha 测试回调中。如果函数是在外部声明的,那么您必须像原始答案中那样显式绑定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2018-07-24
    • 2020-10-28
    相关资源
    最近更新 更多