I have an angular app with version 13 which is using the external dependency js-cookie to set and get some cookies in the browser. As a test environment I am using jest with jest-preset-angular. See all dependencies of the package.json below.
My problem is that in angular 12 the unit tests of the component which is using Cookies.set('test', '123') is running perfectly fine. But with angular 13 while the functionality works and the build (ng build) is running, there is an error message when running jest unit tests:
TypeError: Cookies.set is not a function
Dependencies in package.json:
"dependencies": {
"@angular/animations": "^13.1.2",
"@angular/common": "^13.1.2",
"@angular/compiler": "^13.1.2",
"@angular/core": "^13.1.2",
"@angular/forms": "^13.1.2",
"@angular/platform-browser": "^13.1.2",
"@angular/platform-browser-dynamic": "^13.1.2",
"@angular/router": "^13.1.2",
"rxjs": "~6.6.7",
"tslib": "^2.0.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^13.1.3",
"@angular/cli": "^13.1.3",
"@angular/compiler-cli": "^13.1.2",
"@types/jest": "^27.4.0",
"@types/node": "^14.14.37",
"js-cookie": "^3.0.1",
"codelyzer": "^6.0.0",
"jest": "^27.4.7",
"jest-preset-angular": "11.0.1",
"ts-node": "~9.1.1",
"tslint": "~6.1.0",
"typescript": "4.5.4"
}
Any idea where the change come from? Any known issues when unit testing jest in case of external dependencies with angular13?
I don't want to mock the methods of the external dependency js-cookie.
Example of the angular component:
import {Component} from '@angular/core';
import * as Cookies from 'js-cookie';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent {
constructor() {
Cookies.set('test', '123');
}
}
Unit Test:
import {MyComponent} from './my-component.component';
describe('MyComponent', () => {
const component: MyComponent = new MyComponent();
it('should create', () => {
expect(component).toBeTruthy();
});
});
Ok. Here's what I've figured out.
js-cookie. Please run:and this one to get the TypeScript types:
You're importing it the wrong way:
import * as Cookiesyou just want the default export from the library; not everything else.To address this add the following option in your
tsconfig.jsonunder the "compilerOptions" field:The problem was likely to be that the TypeScript compiler upgrade is noticing something that wasn't noticing before