What are the advantages and disadvantages of placing test files next to the source files they test (in the same src
directory), vs. in a separate tests
directory, mirroring the src
hierarchy?
Having them in the same folder seems to make life easier when it comes to maintenance, but also crowds the source directories.
Option 1: Directory structure when having separate folders for source and tests:
- src +-- item.ts `-- util +-- helper.ts - test +-- item.test.ts `-- util `-- helper.test.ts
Option 2: Directory structure when having both types of files in the same directory:
- src +-- item.ts +-- item.test.ts `-- util +-- helper.ts `-- helper.test.ts
I used to always go with option 1 until trying out angular-cli
and having it generate code files alongside the test files as in option 2, which made me rethink the whole thing.
Regression testing Still, even if that's your only reason for unit testing, I think putting the unit tests in a separate library is the best choice: It gives you a clearer separation of concerns. If you put unit tests in your production library, it will blur the distinction between production code and test code.
Good unit tests should be reproducible and independent from external factors such as the environment or running order. Fast. Developers write unit tests so they can repeatedly run them and check that no bugs have been introduced.
Which of the following is true of unit tests? Unit tests are good for verifying that complicated user interaction behaves as expected. Unit tests are typically used to test small code modules rather than large sections of code. Unit tests are used to test the performance of a block of code.
Option #2 is the way I'd go.
When thinking about the Angular 2 components, I consider them to be a single entity, made up of multiple files. You don't move your HTML / CSS files out to some other directory, away from the component, so why move the unit tests?
I've written a small utility plugin for VSCode that I personally find quite useful - it compresses an Angular 2 component into a single entry on the Explorer view, and adds icons / context menu options for getting to the template / css / unit tests. This helps me see the component as a single unit, comprising multiple parts. Maybe something like that would help keep your directory "clean" if that's what you worry about?
I would encourage you to think about unit tests as PART OF your code, rather than in addition to. They'll be very useful if you can keep on top of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With