Search code examples
javascriptnode.jstestingdirectory-structure

Node.js folder structure: unit tests and e2e tests


Currently, I have the following structure:

/src
/tests/e2e
/specs

Whereas the specs folder I use for unit tests, and the structure inside the specs is the same structure as inside src. (e.g. for /src/user/validator.js there is a /specs/user/validator.spec.js file).

However, it doesn't feel right to me to have two testing folders in the root dir, and I'm wondering if there is any convention in the community about this.

I did go through this thread: Folder structure for a Node.js project. The suggestion there is spec for BDD and tests for unit tests. However, I use BDD (with Jasmine or Mocha) for both: unit tests and e2e tests.


Solution

  • Probably a bit late, but adding this for anyone who may stumble in this question.

    I do agree that having a specs folder at root feels weird for unit tests. If we define that:

    • Unit tests are linked to a single file
    • Integration tests can span across multiple files
    • e2e tests relate to the service as a whole

    Then we can set up a project structure such as:

    ├── e2e/
    ├── src/
    │   ├── controllers/
    │   ├── routes/
    │   └── utils/
    │       ├── foo.js
    │       └── foo.test.js
    └── package.json
        ...
    

    With package.json containing these scripts:

    "test:e2e": "node e2e",
    "test:unit": "mocha src/**/*.test.js",
    "test": "yarn run test:unit && yarn run test:e2e"
    

    In my opinion, this leaves everything nicely separated, where you have each unit test next to what it is testing and e2e overseeing everything as a whole (it is in fact testing src as a whole, therefore it makes sense that it is on the same level!)