'Unit testing angular custom validator
I'm just starting to learn unit testing and I have this problem that causes unit tests not to run. after running ng test it says Executed 0 out of 0 Success here's my code
validator
export function validateUrl(control: FormControl): ValidationErrors | null {
let valid = true;
try{
let str = control.value;
if(str.indexOf('://') === -1){
str = `http://${str}`
new URL(str);
control.setValue(str);
}else{
new URL(control.value);
}
}catch{
valid = false
}
return valid ? null : { invalidUrl: true }
}
spec file
import { TestBed} from "@angular/core/testing";
import { FormControl } from "@angular/forms";
import { validateUrl } from "./web-page-details.component";
describe('maxTextLength', () => {
beforeEach(() => TestBed.configureTestingModule({}))
const control = new FormControl();
it('should return null if input string contains protocol', () => {
control.setValue('http://test.com');
expect(validateUrl(control)).toBeNull();
});
it('should return null if url doesnt contain protocol', () => {
control.setValue('test.com');
expect(validateUrl(control)).toBeNull();
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
