我正在开发一个客户端应用程序,我在创建正确的Karma配置时遇到了麻烦.现在,我的设置如下:
Webpack:使用ts-loader,编译TypeScript,资产等.
Karma:使用webpack插件,加载Webpack配置(使用ts-loader),然后使用Jasmine + PhantomJS运行所有单元测试
单元测试所有运行正常,但我还没有找到一种方法来处理webpack istanbul重映射.Karma-webpacks似乎没有生成源映射以允许重映射发生.任何指针将不胜感激!
Karma配置:
var webpackConfig = require("./webpack.config.js");
delete webpackConfig.entry;
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// Non-automatically bundled libraries
'app/client/js/lib/easeljs.min.js',
'app/client/js/lib/tweenjs.min.js',
// Entry File
'app/client/js/index.ts',
'app/client/html/**/*.html',
// Test files and dependencies
'node_modules/angular-mocks/angular-mocks.js',
'test/client/**/*.spec.js'
],
// preprocess …
Run Code Online (Sandbox Code Playgroud) 我有一个带有一些测试的Angular项目.我的版本是用Gulp编写的.我使用Karma运行测试并生成lcov报告.
然后我使用gulp-sonar插件来运行Sonar.我的声纳配置看起来像这样:
"sonar": {
"host": {
"url": "http://mysonar.example.com.au"
},
"projectKey": "sonar:advertising-test",
"projectName": "advertising-test",
"projectVersion": "1.0.0",
"sources": "app/js",
"javascript": {
"lcov": {
"reportPath": "reports/coverage/lcov.info"
}
},
"exec": {
"maxBuffer": "1048576"
}
}
Run Code Online (Sandbox Code Playgroud)
Sonar运行并分析代码,但在尝试使用以下内容读取lcov报告时失败:
[09:38:58] 09:38:58.322 WARN - Problem during processing LCOV report: can't save DA data for line 0.
java.lang.IllegalArgumentException: Line with number 0 doesn't belong to file app/js/main.js
...
[09:38:58] 09:38:58.324 WARN - Problem during processing LCOV report: can't save DA data for line 65.
java.lang.IllegalArgumentException: Line with number 65 …
Run Code Online (Sandbox Code Playgroud) Gitlab CI要求您指定一个正则表达式来提取语句代码覆盖率(以便它们可以显示它).鉴于下面的构建输出(使用jest和istanbul),我已经设法达到:/Statements.*(\d+\%)/
... (other build output)
=============================== Coverage summary ===============================
Statements : 53.07% ( 95/179 )
Branches : 66.67% ( 28/42 )
Functions : 30.99% ( 22/71 )
Lines : 50.96% ( 80/157 )
================================================================================
... (other build output)
Run Code Online (Sandbox Code Playgroud)
这突出了该部分Statements : 53.07%
(见这里:http://regexr.com/3e9sl).但是,我只需匹配53.07部分,我该怎么做?
我是Angular的单元测试的新手.我得到了karma
代码覆盖率的设置angular-cli
.我运行了命令ng-test并打开了代码覆盖率报告.我看到了1x
,3x
等一起在覆盖报告我的代码行数.请找到我的报道图像.
这是我的测试用例代码 app.component.spec.ts
/* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
});
});
it('should create the app', async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app works!'`, async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app works!');
}));
it('should render …
Run Code Online (Sandbox Code Playgroud) 我的组件是,
getHomePageData() : void{
this.homeservice.getHomePageData()
.subscribe(
data => {
//console.log("response status ################### "+data.status);
//console.log("getUserData response ************ \n"+JSON.stringify(data));
this.defaultFacilityId = data.response.defaultFacilityId;
this.defaultFacilityName = data.response.defaultFacilityName;
this.enterpriseId = data.response.enterpriseId;
this.enterpriseName = data.response.enterpriseName;
this.facilityList = data.response.facilityList;
this.userName = data.response.userName;
this.showDefaultPopoup();
},
error => {
console.error(error);
//this.errorMessage="Technical error - Contact Support team !" ;
}
);
}
Run Code Online (Sandbox Code Playgroud)
所以我的component.spec.ts是,
it('getHomePageData with SUCCESS - getHomePageData()', () => {
backend.connections.subscribe((connection: MockConnection) => {
//expect(connection.request.url).toEqual('http://localhost:8080/MSMTestWebApp/UDM/UdmService/Home/');
expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData');
expect(connection.request.method).toEqual(RequestMethod.Get);
expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
let options = new ResponseOptions({
body:
{
"request": { "url": "/getUserData" …
Run Code Online (Sandbox Code Playgroud) 使用Angular 4,可以测试Component的模板,例如检查单击按钮是否触发了预期的方法和类似的东西.
但是如何将模板包含在测试范围内?默认情况下它们不是(使用Karma + Jasmine + Istanbul的Angular CLI测试).
我使用Karma(目前为v.10.10)和Jasmine进行单元测试,使用Istanbul(通过karma-coverage)进行代码覆盖报告.我注意到在特定情况下代码覆盖率报告者的奇怪行为.
我试图测试的代码大致如下:
/**
* @param {HTMLInputElement} element
*/
var foo = function(element) {
var callback = function() {
// some code
};
element.addEventListener("input", callback);
};
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我在被测元素上调度自定义输入事件并执行回调函数.测试检查回调的影响,测试通过.事实上,即使我console.log("foo")
在回调中放了一个毛茸茸的东西,我也能清楚地看到它被打印出来了.但是,伊斯坦布尔的报告错误地表明回调根本没有执行.
修改测试代码以在事件监听器的回调中使用匿名函数修复了错误行为:
element.addEventListener("input", function() {
callback();
});
Run Code Online (Sandbox Code Playgroud)
但是,我完全鄙视修改应用程序代码的"解决方案",以弥补代码质量控制工具的不足.
有没有一种方法可以让代码覆盖得到正确的选择而无需在匿名函数中包装回调?
我试图在karma框架中使用伊斯坦布尔在karma框架中获取我的打字机代码的代码覆盖率karma.conf中包含了打包的文件,并且通过karma typescript-preprocessor我们能够对打字稿代码进行单元测试和代码覆盖,但代码覆盖率报告来自转换JavaScript代码
如何获取打字稿代码的覆盖率报告?
这是我的karma.conf
档案.
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
preprocessors: {
'src/**/*.ts': ['typescript', 'coverage'],
'test/**/*.ts': ['typescript']
},
typescriptPreprocessor: {
options: {
sourceMap: false, // (optional) Generates corresponding .map file.
target: 'ES5', // (optional) Specify ECMAScript target version: 'ES3' (default), or 'ES5'
module: 'amd', // (optional) Specify module code generation: 'commonjs' or 'amd'
noImplicitAny: true, // (optional) Warn on …
Run Code Online (Sandbox Code Playgroud)我写了一个非常简单的类和一些单元测试.覆盖率报告应该是100%,但我看到75%的分支机构.
我无法弄清楚如何达到100%,我应该在哪里寻找我所缺少的东西.
UPDATE
单元测试:
/* global describe jest it expect */
import GenericDice from '../generic-dice-vanilla';
jest.unmock('../generic-dice-vanilla');
describe('GenericDice', () => {
it('exists.', () => {
expect(GenericDice).toBeDefined();
});
it('has a default face property set to 1', () => {
const dice = new GenericDice();
expect(dice.face).toBe(1);
});
it('has a default rolling property set to true', () => {
const dice = new GenericDice();
expect(dice.rolling).toBe(true);
});
it('has a default animation property set to an empty string', () => {
const dice = new GenericDice(); …
Run Code Online (Sandbox Code Playgroud) 我正在努力为我的打字稿/ mocha/gulp项目获得适当的nyc/istanbul报道.我尝试了很多方法,其中一些似乎无法使用源映射,而其他方法由于ts-node
/ tsc
错误而失败.我目前的设置是:
nyc
相关配置 package.json
"scripts": {
"test:coverage": "nyc npm run test:unit",
"test:unit": "gulp mocha"
}
"nyc": {
"check-coverage": true,
"all": true,
"extension": [
".js",
".jsx",
".ts",
".tsx"
],
"include": [
"src/**/!(*.test.*).[tj]s?(x)"
],
"reporter": [
"html",
"lcov",
"text",
"text-summary"
],
"report-dir": "docs/reports/coverage"
}
Run Code Online (Sandbox Code Playgroud)
gulpfile.js
mocha
相关部分
const SRC_DIR = path.join(__dirname, 'src');
const SRC_FILES = path.join(SRC_DIR, '**', '*.[jt]s?(x)');
const TEST_FILES = path.join(SRC_DIR, '**', '*.test.[jt]s?(x)');
const MOCHA_CONFIG = {
src: [
TEST_FILES
],
watchSrc: [
SRC_FILES,
TEST_FILES
], …
Run Code Online (Sandbox Code Playgroud) istanbul ×10
javascript ×4
angular ×3
typescript ×3
jasmine ×2
karma-runner ×2
browserify ×1
callback ×1
es6-class ×1
gitlab ×1
http ×1
lcov ×1
mocha.js ×1
regex ×1
sonarqube ×1
tsconfig ×1
unit-testing ×1
webpack ×1