[英]What is the purpose of += sign to this code, when you can just do + instead?
[英]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));
});
第一个测试将失败,因为关键语句的执行顺序是:
sharedResource = true;
sharedResource = false;
assert(sharedResource);
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.