Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup variable in mocha suite before each test?

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);
    })
}

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.

like image 391
Tim Avatar asked Aug 02 '26 05:08

Tim


1 Answers

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);
    });
}

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

like image 141
Louis Avatar answered Aug 04 '26 20:08

Louis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!