我已经使用ng new my-app --minimal
来构建一个Angular 5 CLI应用程序。在这样做之后,我发现我确实需要一个spec文件。所以我做的是:
/src/app/my-thing.ts
/src/app/my-thing.spec.ts
describe('MyThing', () => { ... }
醇>
但显然无法找到describe(...)
,因为--minimal
skips setting up tests,所以没有任何东西可以支持它。
如何正确添加与ng test
完美配合的测试设置?
答案 0 :(得分:1)
我更愿意了解是否有基于CLI的解决方案,但是现在我只是推动并使用了一些git,diff和cli magic来查看需要什么起床和跑步。这是一个愚蠢的解决方案:
更新.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
并看到您的测试运行。
希望这有助于某人。