由于 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 4 Unit测试时,对于其中一个使用谷歌地图和agm包的页面显示错误
"在抛出所有\n [object ErrorEvent]之后抛出了一个错误
有谁知道可能是什么问题
在我的 Angular 应用程序中,我绑定了<select>一个反应式表单,如下所示:
<form [formGroup]="myForm">
<select formControlName="myControlName" id="my-select">
<option [value]="value" *ngFor="let value of mySelectValues">{{ value }}</option>
</select>
</form>
Run Code Online (Sandbox Code Playgroud)
在这个阶段,mySelectValues是一个字符串数组。
我像这样进行组件 dom 测试:
it('the select should reflect the form value"', () => {
// I somehow change the form value to 'ABC' here
// and I want to check if the select is correctly showing the change
const select = fixture.nativeElement.querySelector('#my-select');
expect(select.value).toEqual('ABC');
});
Run Code Online (Sandbox Code Playgroud)
这很好用。然而,在某些时候,在某些选择中,我需要将对象作为值,而不是在某些地方使用纯字符串/数字。
所以我改变了我的 HTML 代码来[ngValue]使用[value]:
<option [ngValue]="value" ...
Run Code Online (Sandbox Code Playgroud)
此时,在我的测试中, 的值 …
typescript angular angular-unit-test angular-test angular-testing-library
我创建了一个Angular Directive,它使用CSS选择器自动修剪我的应用程序中的输入,它看起来像......
import { Directive, HostListener, forwardRef } from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
export const TRIM_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TrimInputDirective),
multi: true
};
/**
* The trim accessor for writing trimmed value and listening to changes that is
* used by the {@link NgModel}, {@link FormControlDirective}, and
* {@link FormControlName} directives.
*/
/* tslint:disable */
@Directive({
selector: `
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore)
[formControlName],
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore) …Run Code Online (Sandbox Code Playgroud) javascript unit-testing angular-directive angular angular-unit-test
在运行“ng test”命令时将 angular 7 项目转换为 angular Universal,错误为“ Incomplete: No specs found, , randomized with seed 48751”。尝试了不同的方式提及 stackoverflow,但对我来说没有任何作用。
ERROR in ./src/polyfills.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: ../src/polyfills.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
at AngularCompilerPlugin.getCompiledFile (../node_modules/@ngtools/webpack/src/packages/ngtools/webpack/src/angular_compiler_plugin.ts:1024:15)
at plugin.done.then (../node_modules/@ngtools/webpack/src/packages/ngtools/webpack/src/loader.ts:49:29)
at process._tickCallback (internal/process/next_tick.js:68:7)
@ multi ./src/polyfills.ts ./node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/jit-polyfills.js polyfills[0]
Run Code Online (Sandbox Code Playgroud)
预期输出为 ng test 命令正常运行而不会出现任何问题,以便我的单元测试用例执行。
我尝试了解如何测试这个功能。从(err)=>{ line,它显示为一个未覆盖的声明。
服务.ts
Deletevote(inp) {
console.log(inp);
return this.http.post(environment.apiUrl + '/api/reset/abc', inp).pipe(
catchError((err) => {
console.log('error caught in service');
console.error(err);
return throwError(err);
})
);
}
Run Code Online (Sandbox Code Playgroud)
我已经为正流创建了这个测试用例,但错误部分仍然没有被覆盖。请指导我如何创建错误。
服务规范
const Mockcolor = 'green';
const MockGen = 'male';
it('submitnominGreen', () => {
service.Deletevote(DeleteObj).subscribe((posts) =>{
expect(posts).toEqual([Mockcolor,MockGen], 'should check mock data');
});
const req = httpTestCtrl.expectOne(environment.apiUrl + '/api/reset/abc');
expect(req.request.method).toBe('POST');
expect(req.cancelled).toBeFalsy();
req.flush([Mockcolor,MockGen])
});
Run Code Online (Sandbox Code Playgroud) 在我的角度项目中,我有一个函数
reloadPage(): void {
window.location.reload();
}
Run Code Online (Sandbox Code Playgroud)
因此,每当我需要重新加载页面时,我都会调用此函数。
现在我尝试添加此功能的单元测试,但它不起作用。
it("reloadPage: should be validated", () => {
spyOn(window.location, 'reload').and.callFake(() => {
//test
});
component.reloadPage();
});
Run Code Online (Sandbox Code Playgroud)
它仍然在单元测试中重新加载页面
如何实现该功能的单元测试?任何帮助都将不胜感激。提前致谢
我在编写组件方法测试用例时遇到问题。
如何在其内部和内部测试 Angular 组件方法if else块。subscribe((res) => { ///block}ToasterService
我在我的 component.ts 文件中调用了 Angular 服务方法。在服务呼叫内subscribe(response=>{}。
我已经验证了块中的响应值if else,并根据结果显示烤面包机消息,但我的业力报告说:response=> function not covered并且if else块内未声明未涵盖。
组件.ts
constructor(private userService: UserService,
private toastr: ToastrService) { }
sortUsers(sortKey: string) {
this.userService.getSortUserList(sortKey).subscribe((res) => {
if(res.Success){
this.userService.users = res.Data as User[];
}else{
this.toastr.error(res.Message);
}
});
}
Run Code Online (Sandbox Code Playgroud)
组件规格
it('call sortUser when users are sorted', () => {
const users: User[] = [{
User_Id: 1,
First_Name: 'Madhu Ranjan',
Last_Name: 'Vannia Rajan', …Run Code Online (Sandbox Code Playgroud) 我正在 Angular 中编写 Ag-grid 的单元测试用例,其中有 Angular Grid:外部过滤器,它是切换过滤器复选框。我收到“TypeError:无法读取未定义的属性‘onFilterChanged’”
我正在测试这个方法:
toggleCheckboxMethod({ checked }): void {
isChecked = checked;
this.gridApi.onFilterChanged(); //when this method initiates it causes for test to fail
}
Run Code Online (Sandbox Code Playgroud)
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
HttpClientModule,
HttpClientTestingModule,
AgGridModule.withComponents([]),
MatDialogModule,
BrowserAnimationsModule
],
declarations: [ TestComponent ],
providers: []
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should toggle checkbox', () => {
let isChecked = false;
spyOn(component, 'toggleCheckboxMethod').and.callThrough();
component.toggleCheckboxMethod({ checked: true });
expect(component.toggleCheckboxMethod).toHaveBeenCalled();
expect(isChecked).toEqual(true); …Run Code Online (Sandbox Code Playgroud) angular ×10
angular-test ×3
unit-testing ×3
typescript ×2
ag-grid ×1
angular-cli ×1
angular12 ×1
angular9 ×1
jasmine ×1
javascript ×1
jestjs ×1