在继续描述中的流程之前,如何等待beforeEach执行?

时间:2020-06-03 14:13:34

标签: typescript async-await mocha

我有以下TypeScript文件:

foo.ts

import { shouldBehaveLikeBar } from "./bar";

describe("Foo", function() {
  const wallets: Wallet[];

  beforeEach(async function() {
    wallets = (await ethers.getSigners()) as Wallet[];
  });

  shouldBehaveLikeBar(wallets);
});

bar.ts

export function shouldBehaveLikeBar(wallets: Wallet[]) {
  describe("Bar", function() {
    it("should test something", async function() {
      const something = await callFunctionThatNeeds(wallets[0].address);
      expect(something).to.equal(true);
    });
  });
}

基本上,我需要wallets[0]才能存在于should test something测试套件中。但是没有,我得到了这个错误:

TypeError:无法读取未定义的属性“地址”

我认为在将值传递到beforeEach之前,mocha将等待shouldBehaveLikeBar执行。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我想出了如何实现自己想要的。它涉及使用delayed root suite功能。

这是foo.ts文件的重写方式:

import { shouldBehaveLikeBar } from "./bar";

setTimeout(async function() {
  const wallets: Wallet[] = (await ethers.getSigners()) as Wallet[];

  describe("Foo", function() {
    shouldBehaveLikeBar(wallets);
  });

  run();
}, 1000);

还有一个注意事项:确保已安装@types/mocha软件包,以便TypeScript编译器可以推断run函数的来源。