Mocha测试:如何在beforeEach钩子执行后调用describe?
Mocha测试参数传递问题的合理解决方案
问题背景
原测试代码
// 公共文件中的代码 async function additionalTests(param_test) { it("one more test_1", async() => { }) it("one more test_2", async() => { }) } describe("Tests", async () => { let param_test; before(() => { console.log("before"); }) beforeEach(() => { console.log("beforeEach"); param_test = 20; }) describe("Some describe", async () => { additionalTests(param_test); }) })
问题原因
传递给additionalTests的param_test始终为undefined,因为Mocha的describe属于测试初始化阶段的同步代码,会在before、beforeEach这类运行时钩子执行前就完成调用,此时param_test还未被赋值。
现有方案的缺陷
曾尝试将additionalTests放在it块内调用,虽然能拿到赋值后的param_test,但会导致additionalTests里的it测试嵌套在另一个it内部,违反Mocha的测试结构规范——it测试的直接父级必须是describe。
推荐解决方案
方案一:利用Mocha上下文传递参数
通过Mocha内置的测试上下文(this)传递参数,避免嵌套it的问题,同时保证参数能被正确获取:
// 调整additionalTests,不再直接接收参数,而是在测试中通过上下文获取 async function additionalTests() { it("one more test_1", async function() { // 通过this访问Mocha上下文里的参数 console.log(this.param_test); // 输出20 }) it("one more test_2", async function() { console.log(this.param_test); // 输出20 }) } describe("Tests", function() { before(function() { console.log("before"); }) beforeEach(function() { console.log("beforeEach"); // 将参数赋值到Mocha的上下文对象中 this.param_test = 20; }) describe("Some describe", function() { // 直接调用additionalTests,无需传参 additionalTests(); }) })
注意事项:
- 不要给
describe和钩子函数使用箭头函数,否则会丢失Mocha的上下文this - 每个
it测试里的this都会继承当前describe的上下文,能正确获取beforeEach中赋值的参数
方案二:动态在钩子中添加测试
如果参数是一次性初始化的固定值,可在before钩子中调用additionalTests,确保参数赋值完成后再生成测试:
// 保持additionalTests的参数接收逻辑不变 async function additionalTests(param_test) { it("one more test_1", async() => { console.log(param_test); // 输出20 }) it("one more test_2", async() => { console.log(param_test); // 输出20 }) } describe("Tests", () => { let param_test; before(() => { console.log("before"); // 在此一次性初始化参数 param_test = 20; }) describe("Some describe", () => { // 在before钩子中调用additionalTests,此时参数已赋值 before(() => { additionalTests(param_test); }) }) })
适用场景:
- 参数为固定值,无需在每个测试前更新
- 避免了测试重复生成的问题(若在
beforeEach中调用会导致每次测试都添加新的it)
内容的提问来源于stack exchange,提问作者Giorgi Lagidze
相关产品推荐
相关产品推荐

