0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Mochaのdescribe()をネストしたときにhook関数が実行される順番

Last updated at Posted at 2022-11-25

概要

describe()をネストしたときの before(), after(), beforeEach(), afterEach() が呼ばれる順番を確かめた結果について述べる。 (Mocha公式のhook関数についての説明はこちら)

結論

ネストしても各itで一番外のbeforeEach()、afterEach()が毎回呼ばれてる。
リトライした場合も同じく、一番外のbeforeEach()~afterEach()をやり直している。

実験1

describeをネストし、外・内それぞれのbefore,after,beforeEach,afterEachでログを出してそれらの実行タイミングを確認する。

入力
describe("describe(外)", () => {
  before(() => console.log("外-before"));
  beforeEach(() => console.log("外-beforeEach"));
  after(() => console.log("外-after"));
  afterEach(() => console.log("外-afterEach"));
  describe("describe(内)", () => {
    before(() => console.log("内-before"));
    beforeEach(() => console.log("内-beforeEach"));
    after(() => console.log("内-after"));
    afterEach(() => console.log("内-afterEact"));
    it("it-1", () => console.log("it(1)"));
    it("it-2", () => console.log("it(2)"));
  });
});
出力結果(実行順に出力)
    外-before
        内-before
            外-beforeEach
                内-beforeEach
                        it(1)
                内-afterEact
            外-afterEach
            外-beforeEach
                内-beforeEach
                        it(2)
                内-afterEact
            外-afterEach
        内-after
    外-after

実験2

さらにリトライ入れたらどうなるか。

入力
import { assert } from "chai";

describe("describe(外)", () => {
  before(() => console.log("外-before"));
  beforeEach(() => console.log("外-beforeEach"));
  after(() => console.log("外-after"));
  afterEach(() => console.log("外-afterEach"));
  describe("describe(内)", () => {
    before(() => console.log("内-before"));
    beforeEach(() => console.log("内-beforeEach"));
    after(() => console.log("内-after"));
    afterEach(() => console.log("内-afterEact"));
    it("it-1", function () {
      this.retries(1);
      console.log("it(1) failing");
      assert.fail("it(1)");
    });
    it("it-2", () => console.log("it(2)"));
  });
});

出力結果(実行順に出力)
    外-before
        内-before
            外-beforeEach
                内-beforeEach
                        it(1) failing
                内-afterEact
            外-afterEach
            外-beforeEach
                内-beforeEach
                        it(1) failing
                内-afterEact
            外-afterEach
            外-beforeEach
                内-beforeEach
                        it(2)
                内-afterEact
            外-afterEach
        内-after
    外-after
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?