describe('TemplateDrivenFormsAsyncInsuredComponent', () => { let component: TemplateDrivenFormsAsyncInsuredComponent; let fixture: ComponentFixture<TemplateDrivenFormsAsyncInsuredComponent>;
it('should assign the value of the formControl to property "name" of the insured', () => { // Arrange const value = 'Leo'; const errors = null; // Act component.insuredNameChange(value, errors, insured); // Assert expect(insured.name).toBe(value); });
it('should assign error message "此欄位必填" to property "nameErrorMessage" of the insured when the value of the formControl is empty string', () => { // Arrange const value = ''; const errors = { required: true }; const errorMessage = '此欄位必填'; // Act component.insuredNameChange(value, errors, insured); // Assert expect(insured.nameErrorMessage).toBe(errorMessage); });
it('should assign error message "姓名至少需兩個字以上" to property "nameErrorMessage" of the insured when the value\;s length of the formControl less than 2', () => { // Arrange const value = 'L'; const errors = { minlength: { actualLength: 1, requiredLength: 2 } }; const errorMessage = '姓名至少需兩個字以上'; // Act component.insuredNameChange(value, errors, insured); // Assert expect(insured.nameErrorMessage).toBe(errorMessage); }); });
it('should assign the value of the formControl to property "age" of the insured', () => { // Arrange const age = '18'; const errors = null; // Act component.insuredAgeChange(age, errors, insured); // Assert expect(insured.age).toBe(age); });
it('should assign error message "此欄位必填" to property "ageErrorMessage" of the insured when the value of the formControl is empty string', () => { // Arrange const age = ''; const errors = { required: true }; const errorMessage = '此欄位必填'; // Act component.insuredAgeChange(age, errors, insured); // Assert expect(insured.ageErrorMessage).toBe(errorMessage); }); });
測試結果:
測試單元 - addInsured
這個單元的測試也是相當簡單,基本上只要驗證執行後會新增一個被保人表單的資料即可。
程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
describe('addInsured', () => { it('should add a new insured data into property "insuredList" after being triggered', () => { // Arrange const expectResult: Insured[] = [{ name: '', gender: '', age: '', nameErrorMessage: '', ageErrorMessage: '' }]; // Act component.addInsured(); // Assert expect(component.insuredList).toEqual(expectResult); }); });