user762579
user762579

Reputation:

mocha tests Is it possible to reuse the same before() and after() hooks in all my tests?

I use the same before() and after() root level hooks in all my tests to setup and clear my test-database ... Is there any way to move them into a file and export/import that file ?

Upvotes: 2

Views: 651

Answers (1)

Troy Weber
Troy Weber

Reputation: 1075

Yes. I was able to achieve this behavior by taking advantage of mocha's this context, discussed in their Wiki article about shared behaviors. I am using ts-mocha which accounts for the async/await functionality.

So I wrote functions to login and logout using supertest-session and it looks something like this:

export function authHooks()
{
    const email = UsersSeed[0].email;
    const password = UsersSeed[0].password;

    before(`login ${email}`, async function()
    {
        await this.session.post('/api/account/login')
            .send({ email, password })
            .expect(201);
    });

    after(`logout ${email}`, async function()
    {
        await this.session.get('/api/account/logout')
            .expect(200);
    });
}

Inside of my describe I set up the this.session and in my it-statements I can reuse it. It looks a little like this:

import { expect } from 'chai';
import * as Session from 'supertest-session';
import { authHooks } from './authHooks';

describe('Some Suite', () =>
{
    before(function()
    {
        this.session = new Session(SomeApp);
    });

    after(function()
    {
        this.session.destroy();
    });

    describe('when not authenticated', () =>
    {
        it('returns 403', async function()
        {
            await this.session.get('/api/jobs')
                .expect(403)
                .expect({ statusCode: 403, message: 'Forbidden resource' });
        });
    });

    describe('when authenticated', () =>
    {
        authHooks();

        describe('when finding jobs', () =>
        {
            it('returns all jobs', async function()
            {
                await this.session.get('/api/jobs')
                    .expect(200)
                    .then((response) =>
                    {
                        expect(response.body).to.deep.eq(SomeThing);
                    });
            });
        });
    });
});

I'm not sure if this is the best way to achieve it (I'm not a fan of using function over () => {} personally), but I have confirmed it works.

The above code will not run mainly because I'm protecting code specifics, but hopefully this will provide at least one option for you and maybe someone else can show a better way to do this.

Upvotes: 2

Related Questions