我读了很多关于这个问题的帖子,但我不明白如何修复它.我尝试了很多解决方案,但仍然存在错误.
Details:
/home/work/project/node_modules/ngx-cookie-service/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './cookie-service/cookie.service';
^^^^^^
SyntaxError: Unexpected token export
15 | this.sessionStorage = sessionStorage;
16 | this.localStorage = localStorageService;
> 17 | this.cookieService = cookieService;
| ^
18 | }
19 |
20 | public set(key, value, useSessionStorage = true) {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/myApp/coreModule/services/storageLayer.service.ts:17:30)
at Object.<anonymous> (src/myApp/itemModule/components/category.component.ts:30:32)
所以我把它添加到我的package.json:
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!ngx-cookie-service)"
]
}
问题仍然存在.有人可以帮忙吗?我应该使用“moduleNameMapper”来模拟ngx-cookie-service吗?
非常感谢你 !
最佳答案 我刚刚找到了解决这个问题的方法.
>在node_modules所在的根文件夹中添加一个文件夹__mocks__.
>在__mocks__文件夹中添加ngx-cookie-service.js文件并放置以下代码:
class MockCookieService {
constructor() {
this._cookieReg = {};
}
check(name) {
return this._cookieReg[name] ? true : false;
}
get(name) {
return this._cookieReg[name];
}
getAll() {
return this._cookieReg;
}
set(
name,
value,
expires,
path,
domain,
secure,
sameSite
) {
this._cookieReg[name] = name + '=' + value;
}
delete(name, path, domain) {
delete this._cookieReg[name];
}
deleteAll(path, domain) {
this._cookieReg = {};
}
}
module.exports = {
CookieService: MockCookieService
};
>现在在实际的组件规范文件中,放置以下代码:
import { CookieService } from 'ngx-cookie-service';
jest.genMockFromModule('ngx-cookie-service');
TestBed.configureTestingModule({
declarations: [Your-Component],
providers: [CookieService]
})
>现在运行jest,测试运行正常.