directive:

import { Directive, HostListener, HostBinding, ElementRef } from '@angular/core';

@Directive({
selector: '[credit-card]'
})
export class CreditCardDirective { @HostBinding('style.border')
border: string; @HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) { const input = event.target as HTMLInputElement; let trimmed = input.value.replace(/\s+/g, '');
if (trimmed.length > ) {
trimmed = trimmed.substr(, );
} let numbers = [];
for (let i = ; i < trimmed.length; i += ) {
numbers.push(trimmed.substr(i, ));
} input.value = numbers.join(' '); this.border = '';
if (/[^\d]+/.test(trimmed)) {
this.border = '1px solid red';
} }
}

test:

import { DebugElement, Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { By } from '@angular/platform-browser';
import { CreditCardDirective } from './credit-card.directive'; TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
); @Component({
template: `
<input type="text" [value]="value" credit-card>
`
})
class TestComponent {
value = ;
} describe('CreditCardDirective', () => { let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let el: DebugElement; beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
CreditCardDirective,
TestComponent
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
}); it('should format the string with spaces', () => {
const directive = el.query(By.directive(CreditCardDirective)).nativeElement;
directive.value = '';
directive.dispatchEvent(new Event('input'));
expect(directive.value).toBe('4751 23');
directive.value = '';
directive.dispatchEvent(new Event('input'));
expect(directive.value).toBe('4751 2398 1201 9201');
}); it('should have a max-length of 16 characters', () => {
const directive = el.query(By.directive(CreditCardDirective));
const directiveEl = directive.nativeElement;
directiveEl.value = '';
directiveEl.dispatchEvent(new Event('input'));
expect(directiveEl.value).toBe('4751 2398 1201 9201');
directiveEl.value = 'abscdef';
directiveEl.dispatchEvent(new Event('input'));
const directiveInstance = directive.injector.get(CreditCardDirective);
expect(directiveInstance.border).toContain('1px solid red');
}); });

[Angular] Test Directive的更多相关文章

  1. [Angular 2] Directive intro and exportAs

    First, What is directive, what is the difference between component and directive. For my understandi ...

  2. 关于angular 自定义directive

    关于angular 自定义directive的小结 首先我们创建一个名为"expander"的自定义directive指令: angular.module("myApp& ...

  3. [Angular] Custom directive Form validator

    Create a directive to check no special characters allowed: import {Directive, forwardRef} from '@ang ...

  4. [Angular] Export directive functionalities by using 'exportAs'

    Directive ables to change component behaives and lookings. Directive can also export some APIs which ...

  5. [Angular] Using directive to create a simple Credit card validator

    We will use 'HostListener' and 'HostBinding' to accomplish the task. The HTML: <label> Credit ...

  6. angular service/directive

    <html class=" js cssanimations csstransitions" ng-app="phonecatApp" > < ...

  7. 一个Demo就懂的Angular之directive

    <body> <div ng-controller="myCtrl"> <hello-word></hello-word> < ...

  8. angular 中 directive中的多个指令

    <div ng-controller="ctrl1"> <superman weight length speed>superman</superma ...

  9. Angular中directive——scope选项与绑定策略,这个也经常迷惑的。

    开门见山地说,scope:{}使指令与外界隔离开来,使其模板(template)处于non-inheriting(无继承)的状态,当然除非你在其中使用了transclude嵌入,这点之后的笔记会再详细 ...

随机推荐

  1. HDU 3072--Intelligence System【SCC缩点新构图 &amp;&amp; 求连通全部SCC的最小费用】

    Intelligence System Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Othe ...

  2. 火狐—火狐浏览器中的“HttpWatch”

    在IE下通过HttpWatch能够查看HTTP请求的相关细节.这对我们分析程序的运行效率很有帮助,但是在火狐浏览器中的难道就没有相似的工具了吗?答案是否定的--火狐浏览器中也有.在火狐浏览器中该工具叫 ...

  3. IO流学习笔记

    1.File类 文件和目录路径名的抽象表示形式. 4种构造方法 File(File parent, String child) File(File parent, String child) File ...

  4. C#中选中指定文件并读取类似ini文件的内容

    一.背景 由于项目中需要去读取设备的配置信息,配置文件的内容和INI配置文件的格式类似,所以可以按照INI文件的方式来处理.涉及如何打开一个文件,获取打开的文件的路径问题,并读取选中的文件里边的内容. ...

  5. Elasticsearch入门系列~通过Java一系列操作Elasticsearch

    Elasticsearch索引的创建.数据的增删该查操作 上一章节已经在Linux系统上安装Elasticsearch并且可以外网访问,这节主要通过Java代码操作Elasticsearch 1.创建 ...

  6. 常见c#正则表达式类学习整理

    1.MatchCollection类 用于输入字符串所找到的成功匹配的集合,Regex.Matches 方法返回 MatchCollection 对象 用法 //str:要搜索匹配项的字符串 patt ...

  7. 关于android主线程异常NetworkOnMainThread不能訪问网络

    今天在学习的过程中遇到了NetworkOnMainThread的异常,关于这个异常问题在android sdk 4.0版本号上,这个问题可能比較常见,查了许些资料大多都是大概解说原因,可是没有解说到详 ...

  8. RHEL6安装调试过程中遇到的问题集

    /*** **问题集 2014/6/9 20:55:52** **Autor: Weigong Xu ** ***/ 1. Linux中开启22port: 22port是ssh服务的.你仅仅要启动ss ...

  9. A glance on VDBI

    Just like other thing in data transfter, a resource should have themselves description. And the reso ...

  10. C/S与B/S架构比较

    一C/S 1.C/S概念 C/S是Client/Server的缩写.服务器通常采用高性能的PC.工作站或小型机,并采用大型数据库系统,如Oracle.Sybase.Informix或 SQL Serv ...