我已将Angular 4应用程序迁移到Angular 6,现在测试用例在终端中失败并显示以下错误消息,并且它在浏览器上显示成功.此外,有时测试用例通过而不显示任何错误消息.所以我们可以说我在运行测试时有60%的时间跟踪错误.
Chrome 67.0.3396 (Linux 0.0.0) ERROR
{
"message": {
"isTrusted": true
},
"str": "[object ErrorEvent]"
}
Run Code Online (Sandbox Code Playgroud)
我尝试升级和降级茉莉和茉莉核心
这是我的package.json
{
"name": "anonymos",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^6.0.3",
"@angular/common": "^6.0.3",
"@angular/compiler": "^6.0.3",
"@angular/core": "^6.0.3",
"@angular/forms": "^6.0.3",
"@angular/http": "^6.0.3",
"@angular/platform-browser": "^6.0.3",
"@angular/platform-browser-dynamic": "^6.0.3",
"@angular/router": "^6.0.3",
"@ng-bootstrap/ng-bootstrap": "^2.2.0",
"angular-cookie": "^4.1.0",
"angular-in-memory-web-api": "^0.6.0",
"angular2-cookie": "^1.2.6",
"angular2-recaptcha": "1.1.0",
"body-parser": "1.18.3",
"bootstrap": …Run Code Online (Sandbox Code Playgroud) 零件:
@Component({
selector: 'app-test',
templateUrl: './test.component.html'
})
export class TestComponent implements OnInit {
useCase: string;
constructor(
private route: ActivatedRoute,
) {}
ngOnInit() {
this.route.queryParams.subscribe(p => {
if (p) {
this.useCase = p.u;
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
测试规格
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
AppModule
],
providers: [
{ provide: ActivatedRoute, useValue: ??? }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should create', () …Run Code Online (Sandbox Code Playgroud) 我目前正在使用ngBootstrap的自动完成机制(typeahead).现在我想要对输入事件的每个序列调用一个方法进行单元测试.我的测试用例的错误目前是:Cannot read property 'pipe' of undefined
<input id="locationEdit" type="text" class="form-control"
[(ngModel)]="user.location" name="location [ngbTypeahead]="search"/>
Run Code Online (Sandbox Code Playgroud)
public ngOnInit() {
this.search = (text$: Observable<string>) =>
text$.pipe(
tap(() => {
this.isSearching = true;
this.searchFailed = false;
}),
debounceTime(750),
distinctUntilChanged(),
switchMap(term =>
this.cityService.getLocation(term).pipe(
tap((response) => {
this.searchFailed = response.length === 0;
this.isSearching = false;
})))
);
}
Run Code Online (Sandbox Code Playgroud)
it('should call spy on city search', fakeAsync(() => {
component.user = <User>{uid: 'test', username: 'mleko', location: null, description: null};
const spy = (<jasmine.Spy>cityStub.getLocation).and.returnValue(of['München Bayern']);
fixture.detectChanges(); …Run Code Online (Sandbox Code Playgroud) 我有一个 angular 组件,它将一些数据发布到我们应用程序中的 URL,然后什么都不做,因为没有数据从该帖子返回。我在测试这个时遇到了麻烦,因为通常 HTTP 请求是通过订阅它们返回的 observable 来测试的。在这种情况下不需要暴露。
这是我的组件代码:
shareData(): void {
this.isFinishing = true;
this.myService.sendSharedData$()
.pipe(first())
.subscribe(() => {
//Data s now shared, send the request to finish up everything
this.submitFinishRequest();
}, (e: Error) => this.handleError(e)));
}
private submitFinishRequest(): void {
//submit data to the MVC controller to validate everything,
const data = new FormData();
data.append('ApiToken', this.authService.apiToken);
data.append('OrderId', this.authService.orderId);
this.http.post<void>('/finish', data)
.pipe(first())
.subscribe((d) => {
// The controller should now redirect the app to the logged-out MVC view, so …Run Code Online (Sandbox Code Playgroud) 我正在使用 Jest 测试 Angular 服务。
我可以模拟我的 httpClient,但我有一个问题是我无法使用参数测试 url(例如:“ http://localhost:8080/api/feature/num?id=25663 ”)。
这是我的测试代码:
describe('MyService', () => {
let myService: MyService;
const httpMock = {get: jest.fn(() => of(dataMock))};
const provide = (mock: any): any => mock;
beforeEach(() => {
myService= new MyService(provide(httpMock));
});
test('should created', () => {
expect(myService).toBeTruthy();
});
test('should retrieve one user', (done) => {
const number = 26586;
const url = 'http://localhost:8080/api/feature/num?number=25663';
myService.getNumero(number).subscribe(
res => {
expect(httpMock.get).toBeCalledWith(url);
expect(res.number).toBe(number);
expect(res.city).toEqual('PARIS');
done();
});
});
});
Run Code Online (Sandbox Code Playgroud)
在我的控制台中我有这个错误:
Error: Uncaught [Error: expect(jest.fn()).toBeCalledWith(...expected)
Expected: "http://localhost:8080/api/feature/num?number=25663" …Run Code Online (Sandbox Code Playgroud) 我有一个带标签的组件。我需要导航到一个选项卡,然后测试可查看的输入等。我可以从控制台日志中看到我正在执行的操作正在调用我正在使用以下过程进行监视的函数。我还可以看到这是以正确的顺序发生的。
不幸的是,这会产生一个没有错误的成功测试,根据 ng test 在测试中没有发现任何期望。(规格没有期望)
将期望放在 whenStable 命令之外会使期望在模糊命令之前运行。
it('should call to save changes when project name is blurred',
fakeAsync(() => {
component.ngOnInit();
tick();
const tabLabels = fixture.debugElement.queryAll(By.css('.mat-tab-label'));
console.log(tabLabels);
tabLabels[1].triggerEventHandler('click', null);
fixture.detectChanges();
fixture.whenStable().then(() => {
const projectName = fixture.debugElement.query(By.css('#projectName'));
console.log(projectName);
let mySpy = spyOn(component, 'saveProject');
projectName.triggerEventHandler('blur', null);
console.log('Lowered expectations');
expect(mySpy).toHaveBeenCalled();
});
})
);
Run Code Online (Sandbox Code Playgroud)
这是与测试相关的 HTML。
<!-- HEADER -->
<div class="header accent" fxLayout="row"></div>
<!-- / HEADER -->
<!-- CONTENT -->
<div class="content">
<!-- CENTER -->
<div class="center p-24" fusePerfectScrollbar>
<!-- CONTENT --> …Run Code Online (Sandbox Code Playgroud) 在我的 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
如何订阅 Storybook for Angular 中的组件 Output?
例如,我有这样的组件及其输出操作:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-task',
template: `
<div class="list-item">
<input type="text" [value]="task.title" readonly="true" />
</div>
`,
})
export class TaskComponent {
@Input() task: any;
// tslint:disable-next-line: no-output-on-prefix
@Output()
onPinTask = new EventEmitter<Event>();
// tslint:disable-next-line: no-output-on-prefix
@Output()
onArchiveTask = new EventEmitter<Event>();
}
Run Code Online (Sandbox Code Playgroud)
我还有该组件的 Storybook 文件:
import { Story, Meta } from '@storybook/angular/types-6-0';
import { action } from '@storybook/addon-actions';
import { TaskComponent } from './task.component';
export default { …Run Code Online (Sandbox Code Playgroud) 在 Angular 7 单元测试中,有没有办法async( async(){} )在将异步支持与async..await关键字结合使用时避免双重语法?
我是 angular 的新手,但我是一位经验丰富的程序员,而且我无法选择我喜欢的测试风格。
我想async..await在测试中安全使用,并且我理解以下语法。然而,当指导开发人员接触现代 javascript 和/或async..await双重async(async())语法的概念时,对他们来说是多余的和令人困惑的。他们忽略了外部异步。服务中抛出的异常会导致在实际测试之外报告失败,这很难追踪。
似乎以下之一会更好:
it()应该神奇地支持async..await和包装我的回调,async()这样我就不必考虑它了。it()应该采用一个可选的函数参数(即,asyncor fakeAsync)来包装我的回调。it()变化ita()并且itfa()应该存在,它将用适当的异步助手包装我的回调。it()用 包装我的回调async,另外一个itf()将我的回调包装在fakeAsync.我是否缺少现有的概念或语法?有更好的选择吗?
import { async } from '@angular/core/testing';
describe('MyService', () => {
let service: MyService;
...
it('should get data', async( async() => {
// arrange
let expectedData = { answer: 42 …Run Code Online (Sandbox Code Playgroud) 在我的 TypeScript 应用程序中,我有一个返回 rxjs Observable 的方法,在某些情况下,它可以返回throwError:
import { throwError } from 'rxjs';
// ...
getSomeData(inputValue): Observable<string> {
if (!inputValue) {
return throwError('Missing inputValue!');
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我如何编写测试来涵盖这个特定情况?
angular ×10
angular-test ×10
unit-testing ×3
jasmine ×2
rxjs ×2
typescript ×2
angular6 ×1
angular7 ×1
javascript ×1
jestjs ×1
ng-bootstrap ×1
storybook ×1
testing ×1