ThomasReggi
ThomasReggi

Reputation: 59345

Separation of unit tests and integration tests

I'm interested in creating full mocked unit tests, as well as integration tests that check if some async operation has returned correctly. I'd like one command for the unit tests and one for the integration tests that way I can run them separately in my CI tools. What's the best way to do this? Tools like mocha, and jest only seem to focus on one way of doing things.

The only option I see is using mocha and having two folders in a directory.

Something like:

Then I'd need some way of telling mocha to run all the __unit__ tests in the src directory, and another to tell it to run all the __integration__ tests.

Thoughts?

Upvotes: 22

Views: 7703

Answers (2)

Matt
Matt

Reputation: 74660

Mocha supports directories, file globbing and test name grepping which can be used to create "groups" of tests.

Directories

test/unit/whatever_spec.js
test/int/whatever_spec.js

Then run tests against all js files in a directory with

mocha test/unit
mocha test/int
mocha test/unit test/int

File Prefix

test/unit_whatever_spec.js
test/int_whatever_spec.js

Then run mocha against specific files with

mocha test/unit_*_spec.js
mocha test/int_*_spec.js
mocha

Test Names

Create outer blocks in mocha that describe the test type and class/subject.

describe('Unit::Whatever', function(){})

describe('Integration::Whatever', function(){})

Then run the named blocks with mochas "grep" argument --grep/-g

mocha -g ^Unit::
mocha -g ^Integration::
mocha

It is still useful to keep the file or directory separation when using test names so you can easily differentiate the source file of a failing test.

package.json

Store each test command in your package.json scripts section so it's easy to run with something like yarn test:int or npm run test:int.

{
  scripts: {
    "test": "mocha test/unit test/int",
    "test:unit": "mocha test/unit",
    "test:int": "mocha test/int"
  }
}

Upvotes: 44

Alongkorn
Alongkorn

Reputation: 4197

mocha does not support label or category. You understand correctly. You must create two folders, unit and integration, and call mocha like this

mocha unit mocha integration

Upvotes: -4

Related Questions