While using an already existing project as a POC for unit testing, I encountered a problem at compilation time only when running tests.
I have a couple of string
extension functions with custom title case and whatnot, but one of these which is meant for removing characters from a string is used in a string
utilities class, in a method for cleaning up separator characters from document IDs (such as dots and dashes).
This works perfectly when running Angular application, but the Testing API seems to not be able to find it at that point. If the extension method is used directly in the component, it works as expected, so I know it's not a coding issue.
What could I be doing wrong?
The error (which doesn't happen when running the project. Only when running tests):
string-extensions.ts
(only relevant code):
export {};
declare global {
interface String {
/**
* Remove a/s string/s passada/s por parâmetro desta string
* @param text string/s a ser/em removida/s
*/
emRemove(...text: string[]): string;
}
}
String.prototype.emRemove = function(...text: string[]) {
let retorno = this;
if (text && text.length > 0) {
text.forEach(t => {
retorno = retorno.split(t).join('');
});
}
return retorno;
};
string-utils.ts
(only relevant code):
export default class StringUtils {
/**
* Remove caracteres separadores de documentos e retorna somente o código
* @param documento valor a ser limpo
*/
static getDocumentoLimpo(documento: string): string {
if (this.isNotEmpty(documento)) { // this tests undefined, null only whitespace and actual empty string without using the sometimes misleading falsy
return documento.emRemove('-', '/', '.');
}
return '';
}
}
Project structure:
Edit:
angular.json
(only the projects.architect.test part. If more parts are needed, please ask):
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
I fixed it by adding the extensions to the "include" part of the tsconfig.spec.json
{
"extends": "../tsconfig.json",
...
"include": [
"**/*.spec.ts",
"**/*.d.ts",
"**/*.extension.ts",
...
]
}
Given we have the convention to name our extension files *.extension.ts