我为输入字段写了一个非常简单的自定义验证器:
import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS } from '@angular/forms';
function numberValidator(c: AbstractControl) {
if (!c.value) return null;
return new RegExp('^[1-9][0-9]{6,9}$').test(c.value) ? null : {
validateNumber: {
valid: false
}
}
}
@Directive({
selector: '[number-validator]',
providers: [
{ provide: NG_VALIDATORS, multi: true, useValue: numberValidator }
]
})
export class NumberValidator {
}
Run Code Online (Sandbox Code Playgroud)
我想对这个验证器进行单元测试.我在Angular2页面上阅读了测试属性指令,但没有更改的css或html.我该如何对这个验证器进行单元测试?
unit-testing karma-jasmine angular2-forms angular2-testing angular
在角度2中运行茉莉花规格时出现此错误:
无法读取null茉莉花角2的属性'injector'
堆栈跟踪:
TypeError: Cannot read property 'injector' of null
at TestBed._createCompilerAndModule (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:834:48)
at TestBed._initIfNeeded (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:800:43)
at TestBed.createComponent (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:884:18)
at Function.TestBed.createComponent (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:714:33)
at Object.eval (http://localhost:3002/js/app/landing-page/subcomponents/middle-row.component.spec.js:29:49)
at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:232:26)
at ProxyZoneSpec.onInvoke (http://localhost:3002/node_modules/zone.js/dist/proxy.js:79:39)
at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:231:32)
at Zone.run (http://localhost:3002/node_modules/zone.js/dist/zone.js:114:43)
at Object.eval (http://localhost:3002/node_modules/zone.js/dist/jasmine-patch.js:102:34)
Run Code Online (Sandbox Code Playgroud)
我从官方的angular 2测试文档中复制了此规范:
let comp: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
let de: DebugElement;
let el: HTMLElement;
describe('BannerComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ BannerComponent ], // declare the test component
});
fixture = TestBed.createComponent(BannerComponent);
comp = fixture.componentInstance; …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试一个简单的标题组件,它有一个按钮,并且在聚焦时 - 仅使用 css 可见性属性打开一个下拉列表。
这是html:
<nav class="navigation">
<button type="button">
<span>click here</span>
</button>
<ul>
<li> Text </li>
<li> Text </li>
<li> Text </li>
</ul>
</nav>
Run Code Online (Sandbox Code Playgroud)
这是 scss 样式:
button {
span {
margin-right: 10px;
}
&:focus {
+ ul {
visibility: visible;
}
}
}
ul {
position: absolute;
list-style: none;
z-index: 1000;
visibility: hidden;
transition: visibility 0.1s linear;
background-color: $color-primary;
}
Run Code Online (Sandbox Code Playgroud)
这是测试:
it('should open dropdown on focus', () => {
let button = fixture.debugElement.query(By.css('button'));
button.triggerEventHandler('focus', null);
fixture.detectChanges();
let dropdownElement …Run Code Online (Sandbox Code Playgroud) unit-testing karma-jasmine angular2-testing typescript2.0 angular
所有都在标题中:如何测试组件构造函数中的内容?
为了您的信息,我正在使用一个需要设置的服务,我想看看我在构造函数中调用的2个方法是否被正确调用.
我的组件的构造函数:
constructor(
public router: Router,
private profilService: ProfileService,
private dragula: DragulaService,
private alerter: AlertService
) {
dragula.drag.subscribe((value) => {
this.onDrag(value);
});
dragula.dragend.subscribe((value) => {
this.onDragend(value);
});
}
Run Code Online (Sandbox Code Playgroud) 我有以下功能进行单元测试.我在元件中采用了带有视图子元素的文本框元素,在测试中我需要在setTimeout()调用之后测试我的文本框是否有焦点.
@ViewChild('searchInput') searchInput: ElementRef;
function A(show) {
const self = this;
if (show) {
this.xyz= true;
setTimeout(function () {
self.searchInput.nativeElement.focus();
}, 0);
} else {
self.xyz= false;
self.abc = '';
}
}
Run Code Online (Sandbox Code Playgroud)
这是我正在尝试的测试用例:
it('textbox get focus toggleSearch', async(() => {
let el: DebugElement;
component.toggleSearch(true);
el = fixture.debugElement.query(By.css('#search-input-theme'));
let native: HTMLElement = el.nativeElement;
spyOn(native,'focus');
fixture.whenStable().then(() => {
expect(native.focus).toHaveBeenCalled();
});
}));
Run Code Online (Sandbox Code Playgroud) 我有以下代码......
export class LoginComponent {
userName: string;
password: string;
rememberMe: boolean = false;
constructor( private auth: AuthenticationService,
private router: Router) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试单元测试,但我的第一次尝试失败了....
beforeEach(() => {
router = new Router();
component = new LoginComponent(authService, router);
});
Run Code Online (Sandbox Code Playgroud)
因为它需要Router构造函数的参数.我在这看到 ......
beforeEach(() => addProviders([
APP_ROUTER_PROVIDERS, // must be first
{provide: APP_BASE_HREF, useValue: '/'}, // must be second
{provide: ActivatedRoute, useClass: Mock},
{provide: Router, useClass: Mock}
]));
Run Code Online (Sandbox Code Playgroud)
但我似乎没有APP_ROUTER_PROVIDERS或Mock依赖于任何地方,所以我认为它可能是陈旧的(或者我需要依赖).
我该如何嘲笑这个?它对我正在进行的测试并不重要.
karma-jasmine angular2-routing angular2-testing angular2-router3 angular
我正在测试一个简单的服务。该服务使用另一个服务的2个值。
基本上,我想测试这两个值:isLogged = false和isLogged = true。
是否可以仅更改注入服务的价值,还是我需要做其他事情?(我不知道,所以如果您能带领我前进,我将不胜感激)。
这是我的测试代码:
编辑我找到了解决我的问题的方法。您需要将提供程序注入到注入参数,然后可以根据需要更改其属性。
import { TestBed, async, inject } from '@angular/core/testing';
import { AuthGuardService } from './authguard.service';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
describe('AuthguardService', () => {
let calledUrl = '/logged/main/last';
let authServiceStub = {
isLogged: false,
redirectUrl: calledUrl
};
class RouterStub {
navigate(url: string) { return url; }
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthGuardService,
{ provide: AuthService, useValue: …Run Code Online (Sandbox Code Playgroud) 我想测试实现ControlValueAccessor接口的组件允许[(ngModel)]在我的自定义组件中使用,但问题是通常的输入是正确的但是ngModel- undefined.这是代码示例:
@Component({
template: `
<custom-component
[usualInput]="usualInput"
[(ngModel)]="modelValue"
></custom-component>`
})
class TestHostComponent {
usualInput: number = 1;
modelValue: number = 2;
}
describe('Component test', () => {
let component: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
let de: DebugElement;
let customComponent: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
CustomComponent,
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
}));
});
Run Code Online (Sandbox Code Playgroud)
所以,我希望我的customComponent中的regularInput Input()值等于1(它是真的),并且ngModel值将等于2,但是ngModel = undefined并且在调试之后我知道ControlValueAccessor writeValue方法不会在测试环境中调用(但是它适用于浏览器).那么我该如何解决呢?
我正在尝试测试 HTTP 调用并参考以下页面来编写单元测试:https://angular-2-training-book.rangle.io/handout/testing/services/mockbackend.html
但是当我查看 Angular 网站时,该类似乎MockBackend已被弃用:https://angular.io/api/http/testing/MockBackend
同一网站有不同的方法来测试 HTTP 调用:https://angular-2-training-book.rangle.io/handout/testing/services/alt-http-mocking.html
我还发现了下面一篇有趣的文章(因为我正在尝试测试登录,因此进行 POST 调用):http://jasonwatmore.com/post/2016/11/24/angular-2-mockbackend-example-for-backendless -发展
所以我想知道测试 HTTP 调用的最佳或最新方法是什么?我有点困惑是否使用MockBackend或使用spyOn模拟策略。
unit-testing angular2-services angular2-http angular2-testing angular
我有一个从 ActivatedRoute 的 params 属性获取值的组件。
组件看起来像:
......
constructor(public userRegistration: UserRegistrationService, public userLogin: UserLoginService,
public router: Router, public route: ActivatedRoute) {
}
ngOnInit() {
this.verificationCode = new FormControl('', [Validators.required]);
this.confirmationCodeForm = new FormGroup({verificationCode: this.verificationCode});
//******************************
this.sub = this.route.params.subscribe(params => {
this.email = params['userId'];
});
//******************************
this.errorMessage = null;
}
......
Run Code Online (Sandbox Code Playgroud)
该测试提供了一个 ActivatedRoute 作为模拟该类的“useValue”。测试看起来像:
describe('ConfirmRegistrationComponent', () => {
let component: ConfirmRegistrationComponent;
let fixture: ComponentFixture<ConfirmRegistrationComponent>;
let userRegistrationService: UserRegistrationService;
let userLoginService: UserLoginService;
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule, RouterTestingModule, HttpClientModule], …Run Code Online (Sandbox Code Playgroud)