我用Angular-CLI构建了Angular2项目(beta 20)。
是否有一种方法仅针对一个选定的规范文件运行测试?
我曾经有一个基于Angular2的项目,我可以手动向jasmine文件添加规格。但我不知道如何在因果测试之外设置这个,也不知道如何用Angular-CLI构建将因果测试限制在特定的文件上。
我用Angular-CLI构建了Angular2项目(beta 20)。
是否有一种方法仅针对一个选定的规范文件运行测试?
我曾经有一个基于Angular2的项目,我可以手动向jasmine文件添加规格。但我不知道如何在因果测试之外设置这个,也不知道如何用Angular-CLI构建将因果测试限制在特定的文件上。
当前回答
我自己用grunt解决了这个问题。我有下面的grunt脚本。该脚本所做的是获取要运行的特定测试的命令行参数,并创建test的副本。Ts并把这个特定的测试名称放在那里。
要运行此命令,首先使用以下命令安装grunt-cli:
npm install -g grunt-cli
将以下grunt依赖放在package.json中:
"grunt": "^1.0.1",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-exec": "^2.0.0",
"grunt-string-replace": "^1.3.1"
要运行它,将下面的grunt文件保存为根文件夹中的Gruntfile.js。然后从命令行运行它:
grunt --target=app.component
这将运行app.component.spec.ts。
Grunt文件如下:
/*
This gruntfile is used to run a specific test in watch mode. Example: To run app.component.spec.ts , the Command is:
grunt --target=app.component
Do not specific .spec.ts. If no target is specified it will run all tests.
*/
module.exports = function(grunt) {
var target = grunt.option('target') || '';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['temp.conf.js','src/temp-test.ts'],
copy: {
main: {
files: [
{expand: false, cwd: '.', src: ['karma.conf.js'], dest: 'temp.conf.js'},
{expand: false, cwd: '.', src: ['src/test.ts'], dest: 'src/temp-test.ts'}
],
}
},
'string-replace': {
dist: {
files: {
'temp.conf.js': 'temp.conf.js',
'src/temp-test.ts': 'src/temp-test.ts'
},
options: {
replacements: [{
pattern: /test.ts/ig,
replacement: 'temp-test.ts'
},
{
pattern: /const context =.*/ig,
replacement: 'const context = require.context(\'./\', true, /'+target+'\\\.spec\\\.ts$/);'
}]
}
}
},
'exec': {
sleep: {
//The sleep command is needed here, else webpack compile fails since it seems like the files in the previous step were touched too recently
command: 'ping 127.0.0.1 -n 4 > nul',
stdout: true,
stderr: true
},
ng_test: {
command: 'ng test --config=temp.conf.js',
stdout: true,
stderr: true
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('grunt-exec');
// Default task(s).
grunt.registerTask('default', ['clean','copy','string-replace','exec']);
};
其他回答
对于像我这样正在寻找一种在Angular中运行单一规范的方法并发现了这个SO的人来说更是如此。
根据最新的Angular文档(撰写本文时是v9.0.6), ng test命令有一个——include选项,你可以在其中指定一个*.spec.(ts|tsx)文件目录,也可以只指定一个.spec.(ts|tsx)文件本身。
https://angular.io/cli/test
用,包括
这是一种包含的工作
ng test --include src/app/path-to-component/path-component.component.spec.ts
我试过——主要,但它显示所有失败的结果,而它不是。main会改变主测试。ts文件。
在angular-cli中,你可以运行这个命令,测试只会包含你想要的spec文件。
Ng测试——包括规格文件的路径
只是测试中需要的小变化。SRC文件夹中的Ts文件:
const context = require.context('./', true, /test-example\.spec\.ts$/);
在这里,test-example是我们需要运行的确切文件名
同样地,如果你只需要测试服务文件,你可以替换文件名,比如"/test-example.service"
为像我这样正在寻找一种简单的扩展方法的人添加这个答案:
如果你像我一样使用VS代码,你可以简单地安装Jest Runner扩展,你可以轻松地运行/调试一个测试用例。