在每次测试之前在 mocha 套件中设置变量? [英] Setup variable in mocha suite before each test?

查看:76
本文介绍了在每次测试之前在 mocha 套件中设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想先设置一些变量,然后再执行测试,我找到了这个解决方案,之前运行摩卡设置每个套件而不是在每次测试之前

I would like to setup some variables first, before executing the test, and I found this solution, Running Mocha setup before each suite rather than before each test

但是,我不知道如何将变量传递到我的回调中,他们这样做我会得到未定义

But, I dont know how can I pass the variable into my callback, they way I did I will get undefined

makeSuite('hello', (context) => {
    it('should return', () => {
        assert.strictEqual(1, 1)
    })
})
makeSuite('world', (context) => {
    it('should return', () => {
        console.log(context) // undefined
        assert.strictEqual(1, 1)
    })
})

function makeSuite(name: string, cb: (context: any) => any) {
    let age: string;
    describe(name, () => {
        beforeEach(() => {
            age = '123'
        })

        cb(age);
    })
}

我想将变量传递给回调的原因是,我将有许多私有变量需要在 beforeEach 钩子上设置,而且我不想为所有测试重复我的代码.

The reason why I want to pass the variable into the callback because, I will have many private variables that requires to setup at beforeEach hook, and I dont want to repeat my code for all the tests.

推荐答案

传递给 describe 的回调会立即调用,但您的 beforeEach 钩子会在稍后调用 测试执行时.所以当 cb(age) 被调用时,age 的值为 undefined.age 后来被设置为 "123"cb 之前已经得到了它的值的副本,所以它没有效果.为了让 cb 看到更改,您必须传递对一个对象的引用,然后该对象会发生变异.像这样:

The callbacks passed to describe are called immediately but your beforeEach hook is called later when the test executes. So when cb(age) is called, age has for value undefined. age is later set to "123" but cb has already gotten its copy of the value earlier so it has no effect. In order for cb to see the change you'd have to pass a reference to an object that you then mutate. Something like this:

makeSuite('world', (context) => {
    it('should return', () => {
        console.log(context.age)
    })
})

function makeSuite(name, cb) {
    describe(name, () => {
        let context = {
            age: undefined,
        };
        beforeEach(() => {
            context.age = '123';
        });

        cb(context);
    });
}

(我已经删除了 TypeScript 类型注释,以便它作为纯 JavaScript 运行.无论如何,注释对于解决问题并不重要.)

(I've removed the TypeScript type annotations so that it runs as pure JavaScript. The annotations are not crucial to solving the problem anyway.)

这篇关于在每次测试之前在 mocha 套件中设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆