我有一个服务MetaDataService
@Injectable()
export class MetaDataService {
constructor(private dataService: DataService, private storageService: StorageService, private platform: Platform, private router: Router) {
console.log("MetaData Service initialized..");
}我想用jest框架在单元测试中模拟这个服务,我得到了以下错误:无法解析MetaDataService的所有参数:(?,?);
下面是我的jest配置:
module.exports = {
"preset": "jest-preset-angular",
moduleFileExtensions: ["ts", "html", "js", "json", "mjs"],
extensionsToTreatAsEsm: [".ts"],
"setupFilesAfterEnv": ["<rootDir>/src/setupJest.ts"],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/node_modules/(?!@ionic)",
"<rootDir>/node_modules/(?!@ionic/angular)",
"<rootDir>/node_modules/(?!@ionic|ngx-socket-io/).+\\.js$",
"<rootDir>/dist/"
],
"globals": {
"ts-jest": {
"tsconfig": "<rootDir>/src/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$",
astTransformers: {
before: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer',
]
}
}
},
"transform": {
"^.+\\.(ts|js|mjs|html|svg)$": "babel-jest"
},
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/src/$1",
"^app/(.*)$": "<rootDir>/src/app/$1",
"^assets/(.*)$": "<rootDir>/src/assets/$1",
"^environments/(.*)$": "<rootDir>/src/environments/$1"
},
snapshotSerializers: [
"jest-preset-angular/build/serializers/no-ng-attributes",
"jest-preset-angular/build/serializers/ng-snapshot",
"jest-preset-angular/build/serializers/html-comment"
]
};发布于 2022-03-19 12:16:49
根据您问题中的评论,MockProvider(MetaDataService)为MetaDataService做了一件事。
但是,它在AccessResourceValidatorPipe上失败了,因为它的依赖项不存在于TestBed中。因此,您需要在TestBed.configureTestingModule调用中添加它们。
或者,为了避免这种依赖问题,您可以使用MockBuilder。它模拟所有依赖项。
beforeEach(() => {
return MockBuilder(
TestingComponent,
[
ItsModule,
// only if those two aren't imported in the ItsModule
ModuleOfMetaDataService,
ModuleOfAccessResourceValidatorPipe,
],
);
});https://stackoverflow.com/questions/71512287
复制相似问题