我有一个版本 13 的 Angular 应用程序,它使用外部依赖项 js-cookie在浏览器中设置和获取一些 cookie。作为测试环境,我将jest与jest-preset-angular一起使用。请参阅下面的 package.json 的所有依赖项。
我的问题是,在 Angular 12 中,正在使用的组件的单元测试Cookies.set('test', '123')
运行得非常好。但是,当功能正常工作并且构建(ng build)正在运行时,使用 angular 13,运行 jest 单元测试时会出现错误消息:
TypeError: Cookies.set is not a function
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"
}
知道变化来自哪里吗?在与 angular13 存在外部依赖关系的情况下进行单元测试时是否存在任何已知问题?
我不想模拟外部依赖js-cookie的方法。
角度分量示例:
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');
}
}
单元测试:
import {MyComponent} from './my-component.component';
describe('MyComponent', () => {
const component: MyComponent = new MyComponent();
it('should create', () => {
expect(component).toBeTruthy();
});
});