我使用@ @角度9.0.7,@ngneat/spectator@5.3.1(用玩笑),Inputmask@5.0.3在一个项目中,一切工作的应用程序时,我跑ng serve,甚至ng build,但是当我尝试运行测试套件的失败@Pipe使用Inputmask:
@Pipe:
import { Pipe, PipeTransform } from '@angular/core';
import Inputmask from 'inputmask';
@Pipe({
name: 'appSomePipe',
})
export class SomePipe implements PipeTransform {
transform(value: string): string {
return Inputmask.format(value, {
jitMasking: true,
mask: '1111-1',
});
}
}
Run Code Online (Sandbox Code Playgroud)
@Spec:
import { createPipeFactory, SpectatorPipe } from '@ngneat/spectator/jest';
import { SomePipe } from './some.pipe';
describe('SomePipe', () => {
let spectator: SpectatorPipe<SomePipe>;
const …Run Code Online (Sandbox Code Playgroud) 我收到了这份覆盖摘要
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
================================================================================
Run Code Online (Sandbox Code Playgroud)
我应用了 Angular 文档中指示的更改代码覆盖率:https : //angular.io/guide/testing#enable-code-coverage-report
但我总是得到同样空虚的夏天。
我的 karma.conf.js
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/singleWindow'),
reports: ['html', 'lcovonly', …Run Code Online (Sandbox Code Playgroud) karma-runner karma-jasmine karma-coverage angular angular-test
由于 TestBed.get 在 Angular 9 中已被弃用,因此当使用提供程序覆盖时,以下替代方案是什么
TestBed.configureTestingModule({
providers: [{ provide: MyClass, useClass: MyStub}]
});
const obj : MyStub = TestBed.get(MyClass);
Run Code Online (Sandbox Code Playgroud)
真的是这样还是有更好的方法?
const obj : MyStub = TestBed.inject(MyClass) as unknown as MyStub;
Run Code Online (Sandbox Code Playgroud) 我刚刚在我的 Angular 应用程序的单元/组件测试中修复了几个警告,这些警告使用ng test(使用 Karma/Jasmine)运行。
这个过程可能非常耗时,因为并不总是很明显发现哪个测试用例实际上导致了警告。
所以现在我没有更多的警告,我想知道是否有办法ng test在有任何警告时自动失败。
我正在导入和HttpClient在服务中使用,如下所示:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get("url...");
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我ng test为单元测试运行时,以及那些测试使用该服务时,出现了以下错误:
Error: StaticInjectorError(DynamicTestModule)[HttpClient]:
StaticInjectorError(Platform: core)[HttpClient]:
NullInjectorError: No provider for HttpClient!
HTTP上的Angular 6文档只是说了做我上面的事情。
Angular v4迄今为止,该应用程序是建立在每个版本的基础上并逐渐更新的。目前我们正在进行中Angular v7,最终 CEO 同意编写单元测试,而以前并非如此。
我刚刚创建了一个简单的规范来开始测试并开始在整个项目中实施它,但由于以下错误而卡住了两天:
async() 测试助手需要 AsyncTestZoneSpec,但无法找到。请确保您的环境包含 zone.js/dist/async->test.js
在谷歌上搜索上述错误时,我找到了一些答案,但这与WallaybyjsAngular相关但特定于 Angular。
我试图用全新的angular项目安装来重现这个问题,但真的不能。这可能是在Angular 7.
以下是test.ts文件:
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
// Unfortunately there's no typing for the `__karma__` variable. Just declare it as …Run Code Online (Sandbox Code Playgroud) 我正在编写一个Angular 4组件的测试,它是一个登录表单.可以通过单击"提交"按钮或在任何输入字段中输入来提交表单.此行为由Angular表单指令决定.
我可以编写一个测试用例来验证按钮单击提交表单,但是我无法通过按键事件触发提交行为.
模板:
<form (ngSubmit)="onLoginSubmit()" #loginForm="ngForm">
<div class="form-group">
<label for="userid">User ID</label>
<input type="text" class="form-control" name="userid" id="userid" required
[(ngModel)]="model.userId" #userid="ngModel">
<div [hidden]="userid.valid || userid.untouched" class="alert alert-danger">
User ID is required
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required
[(ngModel)]="model.password" #password="ngModel">
<div [hidden]="password.valid || password.untouched" class="alert alert-danger">
Password is required
</div>
</div>
<button type="submit" class="btn btn-success" [disabled]="loginForm.form.invalid">Submit</button>
Run Code Online (Sandbox Code Playgroud)
规格:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, Component, ViewChild } …Run Code Online (Sandbox Code Playgroud) unit-testing angular2-forms angular-components angular angular-test
我有一个数据服务,它从服务器获取数据并生成多个请求,然后返回一个可观察数组.我想测试数据.
我尝试做的是在我发送的mockrespone数组中包含两个observables我不知道这是否是测试数据的正确方法.
但测试失败,尤其是异步测试块中的最后三个测试
重要提示:我想测试一下,当将charId设置为falsy并将comicsId设置为falsy时,调用方法,订阅它返回的observable,在你模拟了http后,你会得到一个包含两个预期响应的数组.如果charId是真实的,则与预期的4个响应相同.当comicsId真实时,6个预期的响应也是如此
//获取数据的服务
getChar(): Observable<any> {
const Observables = [];
Observables.push(this.http.get('https://gateway.marvel.com:443/v1/public/characters?apikey'));
Observables.push(this.http.get('https://gateway.marvel.com:443/v1/public/comics?apikey'));
if (this.charId) {
Observables.push(this.http.get(`${this.urlChar}${this.charId}${this.apiKey}`));
Observables.push(this.http.get(`${this.urlChar}${this.charId}/comics${this.apiKey}`));
}
if (this.comicsId) {
Observables.push(this.http.get(`${this.urlCom}${this.comicsId}${this.apiKey}`));
Observables.push(this.http.get(`${this.urlCom}${this.comicsId}/creators${this.apiKey}`));
}
console.log([Observable, Observable]);
return Observable.forkJoin(Observables);
}
}
Run Code Online (Sandbox Code Playgroud)
//我的考试
import { async, ComponentFixture, TestBed, getTestBed, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { DataService } from './data.service';
import {
BaseRequestOptions, Http, XHRBackend, HttpModule,
Response, ResponseOptions, RequestMethod
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
describe('DataService', () => {
let …Run Code Online (Sandbox Code Playgroud) 我确实有以下内容beforeEach:
beforeEach(() => {
fixture = TestBed.createComponent(ApplyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
store = TestBed.get<Store<fromAnnouncement.AnnouncementState>>(Store);
store.refreshState();
mockApplicationSelector = store.overrideSelector(selectDraftApplication, testDraftApplication); <-- Try to mock a selector here.
});
Run Code Online (Sandbox Code Playgroud)
选择器 selectDraftApplication 取决于 的功能选择器AnnouncementState,其中有两个实体,其中之一是我使用功能选择器进行子选择以构建我的selectDraftApplication选择器。
当在测试中使用这段代码时,我所有的测试都会崩溃,因为 NgRx 似乎仍然在寻找进一步向上的所有状态,而我希望模拟能够准确地防止这种情况发生。模拟整个 ngrx 实体存储是没有意义的,所以我只希望选择器准确地返回该对象并完成它。我用谷歌搜索了很远很远,但没有得到任何答案。有什么帮助吗?我运行 Angular 8 和 ngrx 8.5.1(该refreshState()功能也不起作用......)
谢谢!
编辑:
export const getAnnouncementState = createFeatureSelector<AnnouncementState>('announcement');
export const getApplicationsState = createSelector(
getAnnouncementState,
(state: AnnouncementState) => state.applications
);
export const selectDraftApplication = createSelector(
getApplicationsState,
(state: ApplicationState) => state.draftApplication
);
Run Code Online (Sandbox Code Playgroud) 在测试我的 Angular 应用程序时,我收到了弃用警告
'已弃用:DI 正在实例化一个令牌“MockLocationStrategy”,该令牌继承了它的 @Injectable 装饰器,但本身不提供。这将在 Angular 的未来版本中成为一个错误。请将@Injectable() 添加到“MockLocationStrategy”类中。
以下是抛出警告的示例测试
describe('BookComponent', () => {
let component: BookComponent;
let fixture: ComponentFixture<BookIssueComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
],
declarations: [BookComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BookComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
我相信警告是因为我更新了我的软件包
Package Current Wanted Latest Location
@angular-devkit/architect 0.1102.11 0.1102.13 0.1200.1 node_modules/@angular-devkit/architect
@angular-devkit/build-angular 0.1102.11 0.1102.13 12.0.1 node_modules/@angular-devkit/build-angular
@angular-eslint/builder 4.2.0 4.3.0 12.0.0 node_modules/@angular-eslint/builder
@angular-eslint/eslint-plugin 4.2.0 4.3.0 12.0.0 node_modules/@angular-eslint/eslint-plugin
@angular-eslint/eslint-plugin-template …Run Code Online (Sandbox Code Playgroud) angular ×10
angular-test ×10
unit-testing ×3
jasmine ×2
javascript ×2
karma-runner ×2
angular-http ×1
angular9 ×1
input-mask ×1
ngrx ×1
typescript ×1