Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

typescript - How to wait for beforeEach to execute before continuing with the flow in describe?

I have the following TypeScript files:

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);
    });
  });
}

Basically, I need wallets[0] to exist in the should test something test suite. But it doesn't, I'm getting this error:

TypeError: Cannot read property 'address' of undefined

I thought that mocha would wait for beforeEach to execute before passing the values onto shouldBehaveLikeBar. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured out how to achieve what I want. It involves using the delayed root suite functionality.

This is how the foo.ts file should be rewritten:

import { shouldBehaveLikeBar } from "./bar";

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

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

  run();
}, 1000);

Also a side note: make sure that you have the @types/mocha package installed, so the TypeScript compiler can infer the provenience of the run function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...