13

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.

Community
  • 1
  • 1
David
  • 2,528
  • 1
  • 23
  • 29

1 Answers1

23

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!)

A Yashwanth
  • 318
  • 4
  • 12
Lucat
  • 2,242
  • 1
  • 30
  • 41
  • 2
    One concern that some people might have with this is that your test files will also be deployed to production. However, if you're deploying with Docker (as is often the case), you can easily avoid this by adding `**/*.test.js` to your `.dockerignore`. So I like the solution that you propose here. – Cameron Hudson Mar 03 '20 at 17:58
  • Good point! However even without docker it should be fairly simple to strip out these files during bundling. – Lucat Mar 03 '20 at 19:20
  • What about test coverage? If one needs to calculate test coverage ratio under src, test files will also be added to coverage ratio, won't they? – ayortanli Sep 28 '20 at 12:20
  • 1
    @ayortanli I believe that packages such as istanbul allow for file exclusion patterns. https://github.com/istanbuljs/nyc#common-configuration-options – Lucat Sep 28 '20 at 12:59
  • 1
    when using the above separation, some libraries are required to move in package.json to dependencies rather than devDependencies (such as mocha, expect etc). What is the best way to resolve this? should I have a separate package.json for the e2e folder altogether? – Natashz Oct 06 '21 at 06:21
  • Where would you define the mentioned integration tests with this structure? – dabo248 Dec 01 '22 at 11:39