Declaration file missing when running ng test

460 views Asked by At

I recently started working on an existing Angular project The unit tests have been broken for quite some time. Unfortunatey, I haven't been able to get them running due to reference errors to an object that is defined in a declaration file. This declaration file is located in the root of the project. At runtime, the actual library is loaded from our development servers and everything works ok.

When running ng test however, Jasmine is complaining about references not being found:

    ReferenceError: SomeObject is not defined
        at <Jasmine>
        at MyService.getDetails (http://localhost:9876/_karma_webpack_/src/app/MyService.service.ts:196:33)

This is the tsconfig for the running app, which is running fine:

{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "experimentalDecorators": true,
    "types": []
  },
  "files": [
    "main.ts",
    "polyfills.ts",
    "someobject.d.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

The test configuration is similar, but gives the above error:

{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "baseUrl": "./",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "someobject.d.ts",
    "polyfills.ts",
    "test.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

The someobject.d.ts file is located in the root of the project, at the same level as polyfills.ts and main.ts.

This is only the second Angular app I have worked on, so I'm not that experienced in this area. It is also the first time that I have encountered a TypeScript declaration file. Most resources I found online are about dealing with declaration files distributed through npm for libraries like lodash. I found little to none information to work with declaration files in the project like this.

I'm looking for some pointers in the right direction to go from here.

Obviously, I edited class and filenames as I'm not at liberty to share source code verbatim.

1

There are 1 answers

0
Rens Verhage On BEST ANSWER

After trying several things, I settled by adding the actual library and include it only for testing in angular.json:

"test": {
    "builder": "@angular-devkit/build-angular:karma",
    "options": {
        ...
        "scripts": [
            "someobject.js"
        ],
        ....
    }
}

This way, the script is available when testing, but not included in production where it is provided by an external service.