danilonet
danilonet

Reputation: 1795

Jasmine with helpers

I'm new on Jasmine testing, I need to test a nodejs express application. I do not find any documentation about jasmine helpers else that are called before all tests.

Just trying I found that adding

beforeAll(async()=>{
   ...
});
afterAll(async()=>{
   ...
});

into my /spec/helpers/myhelper.js these functions are executed after and before all code, but I did not find documentation about this behavior into a helper. Is it a standard behavior?

Is it possible to create my helper function into myhelper.js and call this function during the test? how?

my actual /spec/helpers/myhelper.js is :

let server = require("../../app");
console.log('server started before tests....');

function testMethod(){
    console.log("test helper called");
}

How to call my test helper method from my tests?

I'm using jasmine version 3.2.1

Upvotes: 5

Views: 7347

Answers (1)

mixth
mixth

Reputation: 636

Jasmine test cases are inside describe block.

  • Each describe block has its own beforeAll, afterAll, beforeEach, afterEach.
  • There can be describe inside another describe block.

Typically, I have one spec file which includes one describe block for one unit under test. The setup and teardown of test cases for this unit under test will be in those 4 functions of this describe.

As far as I know, if you want to separate your helper function to the new file, you can just import it normally and execute it in setup and teardown of target describe. But I have never done it since I never encounter any scenario that some classes have same setup or teardown processes.

But here's how you can achieve that:

Create server in helper function

function setupServer() {
  let server = require("../../app");
  console.log('server started before tests....');
  console.log("test helper called");
  return server;
}

module.exports = { setupServer };

In spec file:

const { setupServer } = require('/myhelper');

describe('some unit', () => {
    let server;
    beforeEach(() => {
        server = setupServer();
    });

    it('some test', () => {});
});

Or if you don't need return at all. It can be as short as:

beforeEach(setupServer);

Hope this helps :)

Upvotes: 5

Related Questions