0

Given that angular spec files should reside in the same folder as the normal files, given that I want to reuse some dummy data between some different specs, where should I put it?

Example:

a
  a.service.ts (I want to have some dummy test data returned by this service)
  a.service.spec.ts (and use it in this test)
b
  b.component.spec.ts (and also use it in this test)
c
  c.component.spec.ts (and this one too)
...

I could have this dummy test data defined in each of those spec files, but that would result in a lot of duplication.

I am not sure if there is a good, proper way to define this kind of data.

Saita
  • 964
  • 11
  • 36
  • You should not return dummy test data from the actual service. You should [use a mock](https://angular.io/guide/testing-services#angular-testbed) instead. – rveerd Apr 23 '21 at 14:48
  • @rveerd even in the case of a mock, should I just replicate the mock in each case, even if they are all equal? The issue is finding a proper way to define them once and share it across different spec files. – Saita Apr 23 '21 at 15:00
  • Often a mock is specific for the test because you should only mock functionality that is actually used by the test and the mock should only return data that is actually required for the test. So usually they cannot be shared at all. Also, I find it is more convenient to have the mock defined in the same file as the test. – rveerd Apr 23 '21 at 15:08
  • @Saita I think you should read the documentation to understand what goes where with [Angular](https://angular.io/) good luck. Note: mock data may include test data and may be better suited to another file. – godhar Apr 23 '21 at 15:39

2 Answers2

1

I would just create a ts file and return it as key values with your JSON test data as the value.

export const mockJSON = {
   testkey1: "{\"name\": \"Company List\"}
}

Then you should be able to grab this as an import anywhere else in the code.

godhar
  • 1,128
  • 1
  • 14
  • 34
  • Where would I put this file? Would I call it "something.spec.ts" so angular knows to remove it from my production code? – Saita Apr 23 '21 at 14:59
  • Angular only compiles files that are actually used. If you don't import this file in your app, Angular will not include this file when compiling your app. See also [this question](https://stackoverflow.com/questions/57729518/how-to-get-rid-of-the-warning-ts-file-is-part-of-the-typescript-compilation-but). – rveerd Apr 23 '21 at 15:16
0

Whatever Godhar said will include the file in the build and will increase the size

Better to create a folder say src\test-data and exclude it from the build by adding the following lines in tsconfig.json

"exclude": [ 
    ......,
    "./src/test-data/*.*/*.ts"
]
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85