代码之家  ›  专栏  ›  技术社区  ›  isaacsultan

从beforeach提取函数并分配给'this'变量

  •  0
  • isaacsultan  · 技术社区  · 7 年前

    我的 beforeEach 设置非常冗长,不同文件之间的不同测试用例之间可以重用。

    之前 并且仍然分配给 this

    例子:

    describe(function () {
      beforeEach(async function () {
        this.a = a.new(...);
        this.b = b.new(...);
        this.c = c.new(...);
        ...
      });
      describe("a", function () {
        it("calls a func", async function () {
          await this.a.func();
        });
      });
    });
    

    然后取出尸体 变成 setup 函数(在第二个文件中):

    describe(function () {
      beforeEach(async function () {
        [ this.a, this.b, this.c ] = setup(); 
      });
      ...
    });
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   isaacsultan    7 年前
    //exampleSetup.js
    
    async function setup() {
        const a = a.new(...);
        const b = b.new(...);
        const c = c.new(...);
        return [a, b, c];
    }
    
    module.exports = setup;
    
    //tester.js
    
    const setup = require("exampleSetup");
    let a, b, c;
    beforeEach(async function () {
        [ a, b, c ] = setup()
        ...
      });