我正在对一个 Angular 应用程序进行单元测试,我需要模拟一个服务。我可以毫无问题地模拟服务方法,但是当我尝试以相同的方式模拟属性时,它给了我错误
我的配置服务有一个属性和一种方法,我想模拟该属性,因为我无法生成该值。
服务
@Injectable()
export class ConfigService {
public config = 'iamdirect';
constructor(private http: Http) {
}
public load(): Observable<any> {
return 'Iamokey';
}
}
Run Code Online (Sandbox Code Playgroud)
在角度测试中模拟服务
// mocking config service
configService = TestBed.get(ConfigService);
spyOn(configService, 'load')
.and.returnValue(Observable.of({
contactDetails: {
emailAddress: 'testemail@email.com'
}
}));
Run Code Online (Sandbox Code Playgroud)
当我这样做时,它给了我错误。
spyOn(configService, 'config') //config is the property
.and.returnValue(Observable.of({
contactDetails: {
emailAddress: 'testemail@email.com'
}
}));
Run Code Online (Sandbox Code Playgroud) 我在 ngOnInit 函数中有一个带有 setTimeOut 函数的组件。要为此编写单元测试用例,我使用 tick 和 fakeAsync 来快进 setTimeOut。但是,它不会被执行,而不会调用其他函数 closeAlert()。
组件代码:
export class BannerComponent implements OnInit {
@Input()errorData: any;
@Input()callback: any;
@Input()autoHide: boolean;
constructor() { }
ngOnInit() {
if (this.autoHide) {
setTimeout
(() => {
this.closeAlert();
}, 500);
}
}
closeAlert() {
this.errorData = null;
if (this.callback) {
this.callback();
}
};
}
Run Code Online (Sandbox Code Playgroud)
规范文件:
describe('BannerComponent', () => {
let component: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BannerComponent ]
})
.compileComponents();
}));
beforeEach(async() => {
fixture = …Run Code Online (Sandbox Code Playgroud) 我有一个简单的服务方法,可以调用http post添加 todoList:
add(event: any): Observable<TodoList> {
let todoListToAdd: TodoList = { name: event.target.value, listItems: []};
return this.http.post<TodoList>("https://localhost:44305/todolist", todoListToAdd);
}
Run Code Online (Sandbox Code Playgroud)
我想对这个方法进行单元测试并尝试如下:
import { TestBed, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TodolistService } from './todolist.service';
import { TodoList } from './todolist';
import { HttpResponse } from '@angular/common/http';
describe('TodolistService', () => {
let injector: TestBed;
let service: TodolistService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ TodolistService ] …Run Code Online (Sandbox Code Playgroud) unit-testing karma-jasmine angular angular-unit-test angular-test
使用 Angular v4.4.4,我使用元素(submit)上的事件保存表单<form>。在实时代码上,一切正常。但是,在单元测试中单击 a<button>不会触发(submit)并且测试失败。例如,
组件(伪代码):
@Component({
template: `
<form [formGroup]="formGroup" (submit)="onSave()">
Your name: <input type="text" formControlName="name">
<button id="saveButton">Save</button>
</form>
`
})
export class FooComponent {
public formGroup: FormGroup;
public onSave(): void {
// save and route somewhere
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试(伪代码):
describe('FooComponent', () => {
let fixture, component, _router, routerSpy;
beforeAll(done => (async() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
FormsModule,
ReactiveFormsModule
]
});
fixture = TestBed.createComponent(FooComponent);
component = fixture.componentInstance;
_router = fixture.debugElement.injector.get(Router);
routerSpy …Run Code Online (Sandbox Code Playgroud) 当我们运行 angular 单元测试时,它会启动 chrome 浏览器或 karma.config.js 中提供的浏览器。为什么浏览器需要以及运行 angular 单元测试时到底发生了什么。
我正在尝试修复服务调用的代码覆盖率错误。我遵循两种方法,但犯了一些错误。
下面是我正在编写测试用例的方法
setPrefixSuffixDetails(): void {
this.prefixSuffixDetailSubscription = this.profileBeneficiaryService.getPrefixSuffixDetails()
.subscribe(data => {
if (data.body.prefixlist.length > 0) {
this.prefixConfig.options = data.body.prefixlist;
}
if (data.body.suffixlist.length > 0) {
this.suffixConfig.options = data.body.suffixlist;
}
}, error => {
this.loadingData = false;
this.notificationService.addNotications(error);
});
}
Run Code Online (Sandbox Code Playgroud)
为了进行测试,我正在创建提供程序,以下是我的提供程序
{ provide: ProfileBeneficiaryService, useClass: ProfileServiceStub},
{provide: ProfileBeneficiaryService, useClass: ProfileBenficiaryErrorStub},
Run Code Online (Sandbox Code Playgroud)
一种是成功调用,另一种是错误调用。
beforeEach(async(() => {
TestBed.configureTestingModule({ .............
class ProfileBenficiaryErrorStub {
getPrefixSuffixDetails = function () {
return Observable.throw(Error('Test error'));
}}
class ProfileServiceStub {
getPrefixSuffixDetails = function () {
return Observable.of(this.data);
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是,当我使用两个提供程序时,它只会覆盖错误,如果我不包含错误提供程序,它会覆盖成功 …
我无法理解为什么我的业力测试用例在固定测试用例后重新运行多次。
已断开连接,因为 50000 毫秒内没有消息。Chrome 75.0.3770 (Windows 10.0.0):已执行 131 个,共 251 个已断开连接(1 分 9.028 秒/18.285 秒)
Chrome 75.0.3770 (Windows 10.0.0):已执行 131 个,共 251 个已断开连接(47.273 秒/18.169 秒)
Chrome 75.0.3770 (Windows 10.0.0):已执行 131 个,共 251 个已断开连接(1 分 9.028 秒/18.285 秒)
Chrome 75.0.3770 (Windows 10.0.0):已执行 131 个,共 251 个已断开连接(47.273 秒/18.169 秒)
Chrome 75.0.3770 (Windows 10.0.0):已执行 97 个,共 251 个已断开连接(22.07 秒/19.87 秒)
Chrome 75.0.3770 (Windows 10.0.0):已执行 131 个,共 251 个已断开连接(1 分 9.028 秒/18.285 秒)
Chrome 75.0.3770(Windows 10.0.0):执行了 251 次成功中的 131 次(0 秒/17.406 秒)
Chrome 75.0.3770(Windows …
unit-testing jasmine karma-jasmine package.json angular-unit-test
我收到错误,因为在单元测试时无法读取 angular 7 中激活路由的未定义属性“订阅”。我已经尝试了多种方式,请帮忙。
Observer.of 对我不起作用,因为我有 rx.js 版本 6.3.3
这是我的组件文件 ChildComponent.ts
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-child',
template: `
<h1>Enter your name</h1>
<form
[formGroup]="nameForm"
(ngSubmit)="submitForm(nameForm)"
>
<input
type="text"
formControlName="firstName"
placeholder="first"
>
<input
type="text"
formControlName="lastName"
placeholder="last"
>
<button type="submit">launch to space</button>
</form>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() nameForm: FormGroup;
private abc: number;
constructor(
public route: ActivatedRoute,
) {
this.route.queryParams.subscribe(params => …Run Code Online (Sandbox Code Playgroud) 我正在使用 Karma运行Angular 6 单元测试,下面是我的配置:
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')
],
customLaunchers: {
CustomHeadlessChrome: {
base: "ChromeHeadless",
flags: [
"--headless",
"--disable-gpu",
"--disable-web-security",
"--disable-site-isolation-trials",
"--remote-debugging-port-9222",
"--no-sandbox"
]
}
},
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: …Run Code Online (Sandbox Code Playgroud) angular ×7
unit-testing ×4
angular-test ×2
jasmine ×2
angular5 ×1
angular6 ×1
karma-runner ×1
package.json ×1
typescript ×1