繁体   English   中英

当你可以在#describe范围内运行代码时,Mocha的#beforeEach的目的是什么?

[英]What is the purpose of Mocha's #beforeEach when you can just run code inside the #describe scope?

我正在从这篇文章中学习TDD,作者讨论了Mocha的beforeEach如何在每个断言之前运行代码。 但是我不明白为什么你需要在描述范围内运行代码时才需要这样做。

describe('Test suite for UserComponent', () => {
  beforeEach(() => {
    // Prevent duplication
    wrapper = shallow(<UserComponent
                            name={ 'Reign' }
                            age={ 26 } />);
  });

  it('UserComponent should exist', () => {
    expect(wrapper).to.exist;
  });

  it('Correctly displays the user name and age in paragraphs wrapped under a parent div', () => {
    expect(wrapper.type()).to.equal('div');
    // more code...
  });
});

但不使用beforeEach仍然有效 -

describe('Test suite for UserComponent', () => {

wrapper = shallow(<UserComponent
                        name={ 'Reign' }
                        age={ 26 } />);

  it('UserComponent should exist', () => {
    expect(wrapper).to.exist;
  });

  it('Correctly displays the user name and age in paragraphs wrapped under a parent div', () => {
    expect(wrapper.type()).to.equal('div');
    // more code...
  });
});

beforeEach每次测试之前执行。 当代码从beforeEach移动到传递给describe的函数内部时,这种迭代就会丢失。 但是,并非全部。

某些情况下,直接在传递给describe的函数内执行的代码可以执行与beforeEach钩子相同的任务。 例如,如果它的函数是初始化describe块中测试的本地只读结构,那么你可以跳过beforeEach钩子。

但是,Mocha立即执行所有传递以describe调用的回调,而beforeEach调用注册传递给它的函数以供将来执行 ,并且只有在需要时才会执行。 如果初始化是昂贵的,最好使用beforeEach钩子,因为如果你使用--grep只选择一些测试,或者只使用it.only来运行单个测试,那么只有当它涉及到时,Mocha才会运行钩子。它将实际运行的测试。 如果您在describe有初始化代码,则Mocha不能跳过它,因此您每次都要支付初始化成本。 但是,如果您要使用钩子并且数据是不可变的,那么before的优于beforeEach因为它只运行一次而不是在每次测试之前运行。

再就是在那里直接传递给函数运行的代码的情况下describe是行不通的。 想象一下, sharedResource是一个所有测试都需要使用的资源。 例如,它可能是一个携带国家的第三方图书馆。 有些测试需要将其设置为某种状态。 其他测试需要它处于不同的状态。 这不起作用:

"use strict";

const assert = require('assert');

let sharedResource;

describe("in condition a", () => {
    sharedResource = true;

    it("sharedResource is true", () => assert(sharedResource));
});

describe("in condition b", () => {
    sharedResource = false;

    it("sharedResource is false", () => assert(!sharedResource));
});

第一个测试将失败,因为关键语句的执行顺序是:

  1. sharedResource = true;
  2. sharedResource = false;
  3. assert(sharedResource);
  4. assert(!sharedResource);

使用beforeEach可以轻松解决问题。 运行正常:

"use strict";

const assert = require('assert');

let sharedResource;

describe("in condition a", () => {
    beforeEach(() => {
        sharedResource = true;
    });

    it("sharedResource is true", () => assert(sharedResource));
});

describe("in condition b", () => {
    beforeEach(() => {
        sharedResource = false;
    });

    it("sharedResource is false", () => assert(!sharedResource));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM