我用过 ng new my-app --minimal
搭建一个可玩的 Angular 5 CLI 应用程序。这样做了一段时间后,我发现我确实想要一个规范文件。所以我所做的是:
/src/app/my-thing.ts
跟类/src/app/my-thing.spec.ts
有内容describe('MyThing', () => { ... }
但显然
describe(...)
找不到,因为 --minimal
skips setting up tests ,所以没有什么可以支持它。我如何正确添加一个可以很好地与
ng test
配合使用的测试设置?
最佳答案
我更愿意了解是否有基于 CLI 的解决方案,但现在我只是继续使用一些 git、diff 和 cli 魔术来查看启动和运行所需的内容。这是愚蠢的解决方案:
.angular-cli.json
去除:"class": {
"spec": false
}
.angular-cli.json
设置 "spec": false
至 true
里面到处都是"component"
package.json
:"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
并运行
npm install
安装这些软件包。 karma.conf.js
在项目根目录中:module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
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;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
src/tsconfig.spec.json
:{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"baseUrl": "./",
"module": "commonjs",
"types": [
"jasmine",
"node"
]
},
"files": [
"test.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}
现在你应该可以运行
ng test
并查看您的测试运行情况。希望这可以帮助某人。
关于angular - 向 Angular 'minimal' CLI 应用程序添加测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50707187/