Open Jelledb opened 7 years ago
I usually add test specific content in a folder test-helpers under the root folder of the project.
A mock implementation depends on what you want to test in your unit test.
For me, it is a complete non-sense (and very dangerous) to factorize mock outside a unit test.
Each component (service, directive, component, controller, filter) unit test file MUST have a specific self contained mock implementation for each dependency.
For exemple if you have a unit test for a service named A
, and if this service depends on a service B
and a service C
, your unit test for A
MUST contains a mock implementation for B
and C
inside A
unit test source code file.
You MUST NOT implements service B
mock outside A
unit test because the mock implementation is directly linked with what you want to test for A
(so it is specific).
Notice that this is true in every language or context. It is not specific to angular or javascript. A unit test is by essence self sufficient.
While @MarcLoupias's comment is very solid and generally sound advice, I do create a separate mock file whenever the service that I'm mocking is more generic, like your api.service.js
. The benefit of this approach is that you can quickly improve or update your mock service API if the actual service API changes, without going through each component unit test and having to change it there. This keeps your mock DRY (Don't Repeat Yourself). When your service is being used by multiple components, they can inject your mock service instead of the actual one using AngularJS's dependency injection.
For your question about where to place such a mock file: I don't know what your folder structure looks like, but you could use separate strategies:
*.spec.js*
files are located next to your controllers, you could create a helper folder like @bampakoa suggested*.spec.js
files are located in a test/
folder, you could create a mocks/
folder in there. You could even use _mocks/
, using SASS's import convention
(This is about Angular 1)
So I have this beautiful service called
api.service.js
, and you might guess that this service is used in alot of tests. So I thought to create a mock for it, so it can be reused by many tests, but I'm not sure where to leave the mock in the folder structure. Does anyone have a suggestion?