describe('getErrorMessage', () => { it('should get empty string when the value is correct', () => { // Arrange const formControl = new FormControl(''); const expectedMessage = ''; // Act const message = component.getErrorMessage(formControl); // Assert expect(message).toBe(expectedMessage); });
it('should get empty string when the value is empty string but the form control is pristine', () => { // Arrange const formControl = new FormControl('', [Validators.required]); const expectedMessage = ''; // Act const message = component.getErrorMessage(formControl); // Assert expect(message).toBe(expectedMessage); });
it('should get "此欄位必填" when the value is empty string but the form control', () => { // Arrange const formControl = new FormControl('', [Validators.required]); const expectedMessage = '此欄位必填'; // Act formControl.markAsDirty(); const message = component.getErrorMessage(formControl); // Assert expect(message).toBe(expectedMessage); });
it('should get "格式有誤,請重新輸入" when the value is empty string but the form control', () => { // Arrange const formControl = new FormControl('whatever', [Validators.pattern('/^\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b$/gi')]); const expectedMessage = '格式有誤,請重新輸入'; // Act formControl.markAsDirty(); const message = component.getErrorMessage(formControl); // Assert expect(message).toBe(expectedMessage); });
it('should get "密碼長度最短不得低於8碼" when the value is empty string but the form control', () => { // Arrange const formControl = new FormControl('abc', [Validators.minLength(8)]); const expectedMessage = '密碼長度最短不得低於8碼'; // Act formControl.markAsDirty(); const message = component.getErrorMessage(formControl); // Assert expect(message).toBe(expectedMessage); });
it('should get "密碼長度最長不得超過16碼" when the value is empty string but the form control', () => { // Arrange const formControl = new FormControl('12345678901234567', [Validators.maxLength(16)]); const expectedMessage = '密碼長度最長不得超過16碼'; // Act formControl.markAsDirty(); const message = component.getErrorMessage(formControl); // Assert expect(message).toBe(expectedMessage); }); });