是由于缺少对应的依赖或配置导致的。在Angular 2项目中,使用Jasmine进行单元测试时,需要引入一些依赖和配置,以使测试代码能够正确运行。
解决这个问题的步骤如下:
tsconfig.spec.json
文件,并添加以下内容:{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}src/test.ts
文件,并添加以下内容:import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';declare const require: any;
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
const context = require.context('./', true, /.spec.ts$/);
context.keys().map(context);
karma.conf.js
文件中,确保已经正确配置了Jasmine测试框架。可以参考以下示例配置:module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/my-app'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};完成以上步骤后,重新运行Jasmine测试,应该就不会再出现意外的标记“Import”问题了。
关于Jasmine的更多信息和用法,请参考腾讯云的相关产品和文档:
领取专属 10元无门槛券
手把手带您无忧上云