Unit test angular directive with a form












0















I have a directive which has a form property. The directive is put on the submit button for the form, and listens to click events. When the submit button is clicked, the directive checks if the form is valid and prevents the click event bubbling up to the ngSubmit handler if it's not. It also marks each form control as dirty so validation messages show.



The directive works fine and I'd like to add unit tests, but I can't work out how to set up a form containing a submit button. This is my test as it stands so far, but I can't work out how to relate the NgForm which the directive takes with the fake form I've created which contains the button.



describe('ValidateBeforeSubmitDirective', () => {

let fakeSubmitButtonRef: ElementRef<HTMLButtonElement>;
let fakeForm: HTMLFormElement;

beforeEach(() => {
const fakeSubmitButton = document.createElement('BUTTON') as HTMLButtonElement;
fakeSubmitButton.type = 'submit';
fakeSubmitButtonRef = new ElementRef(fakeSubmitButton);

fakeForm = document.createElement('form');
fakeForm.appendChild(fakeSubmitButton);
});

it('should bubble click event to the submit method if form is valid', () => {
//arrange
const directive = new ValidateBeforeSubmitDirective(fakeSubmitButtonRef);
directive.form = new NgForm(, );
spyOn(directive.form, 'ngSubmit');
expect(directive.form.valid).toBe(true, 'Test has been set up incorrectly, the form should be valid for this test.');

//*** What do I need to do to link my NgForm with fakeForm? ***

//act
fakeSubmitButtonRef.nativeElement.click();

//assert
expect(directive.form.ngSubmit).toHaveBeenCalled();
});
});


For reference, this is my directive code:



@Directive({
selector: '[appValidateBeforeSubmit]'
})
export class ValidateBeforeSubmitDirective {

/**
* @param element This will be the element on which the directive is being used.
*/
constructor(private readonly element: ElementRef<HTMLButtonElement>) { }

@Input('appValidateBeforeSubmit')
form: NgForm;

@HostListener('click', ['$event'])
private onClick(event: Event) {

if (!this.form.valid) {
Object.keys(this.form.controls).forEach(key => {
this.form.controls[key].markAsDirty();
});
}

return this.form.valid; //if false, this will prevent the event from bubbling up to the ngSubmit handler
}
}


It is used as follows:



<form #componentTypeForm="ngForm" (ngSubmit)="ok()">
<button type="submit" [appValidateBeforeSubmit]="componentTypeForm">Submit</button>
</form>


Any ideas how I can set up a form within my test so that the button click event bubbles up to the form's ngSubmit handler?










share|improve this question



























    0















    I have a directive which has a form property. The directive is put on the submit button for the form, and listens to click events. When the submit button is clicked, the directive checks if the form is valid and prevents the click event bubbling up to the ngSubmit handler if it's not. It also marks each form control as dirty so validation messages show.



    The directive works fine and I'd like to add unit tests, but I can't work out how to set up a form containing a submit button. This is my test as it stands so far, but I can't work out how to relate the NgForm which the directive takes with the fake form I've created which contains the button.



    describe('ValidateBeforeSubmitDirective', () => {

    let fakeSubmitButtonRef: ElementRef<HTMLButtonElement>;
    let fakeForm: HTMLFormElement;

    beforeEach(() => {
    const fakeSubmitButton = document.createElement('BUTTON') as HTMLButtonElement;
    fakeSubmitButton.type = 'submit';
    fakeSubmitButtonRef = new ElementRef(fakeSubmitButton);

    fakeForm = document.createElement('form');
    fakeForm.appendChild(fakeSubmitButton);
    });

    it('should bubble click event to the submit method if form is valid', () => {
    //arrange
    const directive = new ValidateBeforeSubmitDirective(fakeSubmitButtonRef);
    directive.form = new NgForm(, );
    spyOn(directive.form, 'ngSubmit');
    expect(directive.form.valid).toBe(true, 'Test has been set up incorrectly, the form should be valid for this test.');

    //*** What do I need to do to link my NgForm with fakeForm? ***

    //act
    fakeSubmitButtonRef.nativeElement.click();

    //assert
    expect(directive.form.ngSubmit).toHaveBeenCalled();
    });
    });


    For reference, this is my directive code:



    @Directive({
    selector: '[appValidateBeforeSubmit]'
    })
    export class ValidateBeforeSubmitDirective {

    /**
    * @param element This will be the element on which the directive is being used.
    */
    constructor(private readonly element: ElementRef<HTMLButtonElement>) { }

    @Input('appValidateBeforeSubmit')
    form: NgForm;

    @HostListener('click', ['$event'])
    private onClick(event: Event) {

    if (!this.form.valid) {
    Object.keys(this.form.controls).forEach(key => {
    this.form.controls[key].markAsDirty();
    });
    }

    return this.form.valid; //if false, this will prevent the event from bubbling up to the ngSubmit handler
    }
    }


    It is used as follows:



    <form #componentTypeForm="ngForm" (ngSubmit)="ok()">
    <button type="submit" [appValidateBeforeSubmit]="componentTypeForm">Submit</button>
    </form>


    Any ideas how I can set up a form within my test so that the button click event bubbles up to the form's ngSubmit handler?










    share|improve this question

























      0












      0








      0








      I have a directive which has a form property. The directive is put on the submit button for the form, and listens to click events. When the submit button is clicked, the directive checks if the form is valid and prevents the click event bubbling up to the ngSubmit handler if it's not. It also marks each form control as dirty so validation messages show.



      The directive works fine and I'd like to add unit tests, but I can't work out how to set up a form containing a submit button. This is my test as it stands so far, but I can't work out how to relate the NgForm which the directive takes with the fake form I've created which contains the button.



      describe('ValidateBeforeSubmitDirective', () => {

      let fakeSubmitButtonRef: ElementRef<HTMLButtonElement>;
      let fakeForm: HTMLFormElement;

      beforeEach(() => {
      const fakeSubmitButton = document.createElement('BUTTON') as HTMLButtonElement;
      fakeSubmitButton.type = 'submit';
      fakeSubmitButtonRef = new ElementRef(fakeSubmitButton);

      fakeForm = document.createElement('form');
      fakeForm.appendChild(fakeSubmitButton);
      });

      it('should bubble click event to the submit method if form is valid', () => {
      //arrange
      const directive = new ValidateBeforeSubmitDirective(fakeSubmitButtonRef);
      directive.form = new NgForm(, );
      spyOn(directive.form, 'ngSubmit');
      expect(directive.form.valid).toBe(true, 'Test has been set up incorrectly, the form should be valid for this test.');

      //*** What do I need to do to link my NgForm with fakeForm? ***

      //act
      fakeSubmitButtonRef.nativeElement.click();

      //assert
      expect(directive.form.ngSubmit).toHaveBeenCalled();
      });
      });


      For reference, this is my directive code:



      @Directive({
      selector: '[appValidateBeforeSubmit]'
      })
      export class ValidateBeforeSubmitDirective {

      /**
      * @param element This will be the element on which the directive is being used.
      */
      constructor(private readonly element: ElementRef<HTMLButtonElement>) { }

      @Input('appValidateBeforeSubmit')
      form: NgForm;

      @HostListener('click', ['$event'])
      private onClick(event: Event) {

      if (!this.form.valid) {
      Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
      });
      }

      return this.form.valid; //if false, this will prevent the event from bubbling up to the ngSubmit handler
      }
      }


      It is used as follows:



      <form #componentTypeForm="ngForm" (ngSubmit)="ok()">
      <button type="submit" [appValidateBeforeSubmit]="componentTypeForm">Submit</button>
      </form>


      Any ideas how I can set up a form within my test so that the button click event bubbles up to the form's ngSubmit handler?










      share|improve this question














      I have a directive which has a form property. The directive is put on the submit button for the form, and listens to click events. When the submit button is clicked, the directive checks if the form is valid and prevents the click event bubbling up to the ngSubmit handler if it's not. It also marks each form control as dirty so validation messages show.



      The directive works fine and I'd like to add unit tests, but I can't work out how to set up a form containing a submit button. This is my test as it stands so far, but I can't work out how to relate the NgForm which the directive takes with the fake form I've created which contains the button.



      describe('ValidateBeforeSubmitDirective', () => {

      let fakeSubmitButtonRef: ElementRef<HTMLButtonElement>;
      let fakeForm: HTMLFormElement;

      beforeEach(() => {
      const fakeSubmitButton = document.createElement('BUTTON') as HTMLButtonElement;
      fakeSubmitButton.type = 'submit';
      fakeSubmitButtonRef = new ElementRef(fakeSubmitButton);

      fakeForm = document.createElement('form');
      fakeForm.appendChild(fakeSubmitButton);
      });

      it('should bubble click event to the submit method if form is valid', () => {
      //arrange
      const directive = new ValidateBeforeSubmitDirective(fakeSubmitButtonRef);
      directive.form = new NgForm(, );
      spyOn(directive.form, 'ngSubmit');
      expect(directive.form.valid).toBe(true, 'Test has been set up incorrectly, the form should be valid for this test.');

      //*** What do I need to do to link my NgForm with fakeForm? ***

      //act
      fakeSubmitButtonRef.nativeElement.click();

      //assert
      expect(directive.form.ngSubmit).toHaveBeenCalled();
      });
      });


      For reference, this is my directive code:



      @Directive({
      selector: '[appValidateBeforeSubmit]'
      })
      export class ValidateBeforeSubmitDirective {

      /**
      * @param element This will be the element on which the directive is being used.
      */
      constructor(private readonly element: ElementRef<HTMLButtonElement>) { }

      @Input('appValidateBeforeSubmit')
      form: NgForm;

      @HostListener('click', ['$event'])
      private onClick(event: Event) {

      if (!this.form.valid) {
      Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
      });
      }

      return this.form.valid; //if false, this will prevent the event from bubbling up to the ngSubmit handler
      }
      }


      It is used as follows:



      <form #componentTypeForm="ngForm" (ngSubmit)="ok()">
      <button type="submit" [appValidateBeforeSubmit]="componentTypeForm">Submit</button>
      </form>


      Any ideas how I can set up a form within my test so that the button click event bubbles up to the form's ngSubmit handler?







      angular jasmine






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Oct 18 '18 at 14:49









      TimTim

      1,19921630




      1,19921630
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Someone did post an answer which put me on the right lines, but they've sadly deleted their answer so I can't give them credit. They pointed out that directives should be tested using a dummy component which is defined within the test file. I have created a component whose template is a form with an input, and I have been able to test the behaviour of the directive by testing the component.



          This is my working test code:



          import { NgForm, FormsModule } from '@angular/forms';
          import { Component } from '@angular/core';
          import { ComponentFixture, TestBed, async } from '@angular/core/testing';
          import { ValidateBeforeSubmitDirective } from './validate-before-submit.directive';

          @Component({
          //The input on this form is required, so we can easily set the form validity by giving it an empty/non-empty string.
          template: `<form #testForm="ngForm">
          <input name="providedValue" [(ngModel)]="providedValue" type="text" required />
          <button type="submit" [appValidateBeforeSubmit]="testForm">Submit</button>
          </form>`
          })
          class TestValidateBeforeSubmitComponent {
          providedValue: string;
          }

          describe('ValidateBeforeSubmitDirective', () => {
          let form: NgForm;
          let fixture: ComponentFixture<TestValidateBeforeSubmitComponent>;

          beforeEach(() => {
          fixture = TestBed.configureTestingModule({
          declarations: [ValidateBeforeSubmitDirective, TestValidateBeforeSubmitComponent],
          imports: [FormsModule],
          providers: [NgForm, HTMLButtonElement]
          }).createComponent(TestValidateBeforeSubmitComponent);

          const formElement = fixture.debugElement.children[0];
          form = formElement.injector.get(NgForm);

          fixture.detectChanges(); // initial binding
          });

          it('should allow submission of a valid form', async(() => {
          //arrange
          fixture.componentInstance.providedValue = 'Arbitrary content'; //valid value
          fixture.detectChanges();
          fixture.whenStable().then(() => {
          expect(form.valid).toBe(true, 'Test has been set up incorrectly, form should be valid.');

          //act
          const buttonElement = fixture.debugElement.children[0].children[1];
          const button = buttonElement.nativeElement;
          button.click();

          //assert
          expect(form.submitted).toBe(true, 'Clicking the submit button on a valid form should have submitted the form.');
          });
          }));

          it('should prevent submission of an invalid form', async(() => {
          //arrange
          fixture.componentInstance.providedValue = ''; //invalid value
          fixture.detectChanges();
          fixture.whenStable().then(() => {
          expect(form.valid).toBe(false, 'Test has been set up incorrectly, form should be invalid.');

          //act
          const buttonElement = fixture.debugElement.children[0].children[1];
          const button = buttonElement.nativeElement;
          button.click();

          //assert
          expect(form.submitted).toBe(false, 'The directive should prevent an invalid form from submitting when the submit button is clicked.');
          });
          }));
          });





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52876748%2funit-test-angular-directive-with-a-form%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Someone did post an answer which put me on the right lines, but they've sadly deleted their answer so I can't give them credit. They pointed out that directives should be tested using a dummy component which is defined within the test file. I have created a component whose template is a form with an input, and I have been able to test the behaviour of the directive by testing the component.



            This is my working test code:



            import { NgForm, FormsModule } from '@angular/forms';
            import { Component } from '@angular/core';
            import { ComponentFixture, TestBed, async } from '@angular/core/testing';
            import { ValidateBeforeSubmitDirective } from './validate-before-submit.directive';

            @Component({
            //The input on this form is required, so we can easily set the form validity by giving it an empty/non-empty string.
            template: `<form #testForm="ngForm">
            <input name="providedValue" [(ngModel)]="providedValue" type="text" required />
            <button type="submit" [appValidateBeforeSubmit]="testForm">Submit</button>
            </form>`
            })
            class TestValidateBeforeSubmitComponent {
            providedValue: string;
            }

            describe('ValidateBeforeSubmitDirective', () => {
            let form: NgForm;
            let fixture: ComponentFixture<TestValidateBeforeSubmitComponent>;

            beforeEach(() => {
            fixture = TestBed.configureTestingModule({
            declarations: [ValidateBeforeSubmitDirective, TestValidateBeforeSubmitComponent],
            imports: [FormsModule],
            providers: [NgForm, HTMLButtonElement]
            }).createComponent(TestValidateBeforeSubmitComponent);

            const formElement = fixture.debugElement.children[0];
            form = formElement.injector.get(NgForm);

            fixture.detectChanges(); // initial binding
            });

            it('should allow submission of a valid form', async(() => {
            //arrange
            fixture.componentInstance.providedValue = 'Arbitrary content'; //valid value
            fixture.detectChanges();
            fixture.whenStable().then(() => {
            expect(form.valid).toBe(true, 'Test has been set up incorrectly, form should be valid.');

            //act
            const buttonElement = fixture.debugElement.children[0].children[1];
            const button = buttonElement.nativeElement;
            button.click();

            //assert
            expect(form.submitted).toBe(true, 'Clicking the submit button on a valid form should have submitted the form.');
            });
            }));

            it('should prevent submission of an invalid form', async(() => {
            //arrange
            fixture.componentInstance.providedValue = ''; //invalid value
            fixture.detectChanges();
            fixture.whenStable().then(() => {
            expect(form.valid).toBe(false, 'Test has been set up incorrectly, form should be invalid.');

            //act
            const buttonElement = fixture.debugElement.children[0].children[1];
            const button = buttonElement.nativeElement;
            button.click();

            //assert
            expect(form.submitted).toBe(false, 'The directive should prevent an invalid form from submitting when the submit button is clicked.');
            });
            }));
            });





            share|improve this answer




























              0














              Someone did post an answer which put me on the right lines, but they've sadly deleted their answer so I can't give them credit. They pointed out that directives should be tested using a dummy component which is defined within the test file. I have created a component whose template is a form with an input, and I have been able to test the behaviour of the directive by testing the component.



              This is my working test code:



              import { NgForm, FormsModule } from '@angular/forms';
              import { Component } from '@angular/core';
              import { ComponentFixture, TestBed, async } from '@angular/core/testing';
              import { ValidateBeforeSubmitDirective } from './validate-before-submit.directive';

              @Component({
              //The input on this form is required, so we can easily set the form validity by giving it an empty/non-empty string.
              template: `<form #testForm="ngForm">
              <input name="providedValue" [(ngModel)]="providedValue" type="text" required />
              <button type="submit" [appValidateBeforeSubmit]="testForm">Submit</button>
              </form>`
              })
              class TestValidateBeforeSubmitComponent {
              providedValue: string;
              }

              describe('ValidateBeforeSubmitDirective', () => {
              let form: NgForm;
              let fixture: ComponentFixture<TestValidateBeforeSubmitComponent>;

              beforeEach(() => {
              fixture = TestBed.configureTestingModule({
              declarations: [ValidateBeforeSubmitDirective, TestValidateBeforeSubmitComponent],
              imports: [FormsModule],
              providers: [NgForm, HTMLButtonElement]
              }).createComponent(TestValidateBeforeSubmitComponent);

              const formElement = fixture.debugElement.children[0];
              form = formElement.injector.get(NgForm);

              fixture.detectChanges(); // initial binding
              });

              it('should allow submission of a valid form', async(() => {
              //arrange
              fixture.componentInstance.providedValue = 'Arbitrary content'; //valid value
              fixture.detectChanges();
              fixture.whenStable().then(() => {
              expect(form.valid).toBe(true, 'Test has been set up incorrectly, form should be valid.');

              //act
              const buttonElement = fixture.debugElement.children[0].children[1];
              const button = buttonElement.nativeElement;
              button.click();

              //assert
              expect(form.submitted).toBe(true, 'Clicking the submit button on a valid form should have submitted the form.');
              });
              }));

              it('should prevent submission of an invalid form', async(() => {
              //arrange
              fixture.componentInstance.providedValue = ''; //invalid value
              fixture.detectChanges();
              fixture.whenStable().then(() => {
              expect(form.valid).toBe(false, 'Test has been set up incorrectly, form should be invalid.');

              //act
              const buttonElement = fixture.debugElement.children[0].children[1];
              const button = buttonElement.nativeElement;
              button.click();

              //assert
              expect(form.submitted).toBe(false, 'The directive should prevent an invalid form from submitting when the submit button is clicked.');
              });
              }));
              });





              share|improve this answer


























                0












                0








                0







                Someone did post an answer which put me on the right lines, but they've sadly deleted their answer so I can't give them credit. They pointed out that directives should be tested using a dummy component which is defined within the test file. I have created a component whose template is a form with an input, and I have been able to test the behaviour of the directive by testing the component.



                This is my working test code:



                import { NgForm, FormsModule } from '@angular/forms';
                import { Component } from '@angular/core';
                import { ComponentFixture, TestBed, async } from '@angular/core/testing';
                import { ValidateBeforeSubmitDirective } from './validate-before-submit.directive';

                @Component({
                //The input on this form is required, so we can easily set the form validity by giving it an empty/non-empty string.
                template: `<form #testForm="ngForm">
                <input name="providedValue" [(ngModel)]="providedValue" type="text" required />
                <button type="submit" [appValidateBeforeSubmit]="testForm">Submit</button>
                </form>`
                })
                class TestValidateBeforeSubmitComponent {
                providedValue: string;
                }

                describe('ValidateBeforeSubmitDirective', () => {
                let form: NgForm;
                let fixture: ComponentFixture<TestValidateBeforeSubmitComponent>;

                beforeEach(() => {
                fixture = TestBed.configureTestingModule({
                declarations: [ValidateBeforeSubmitDirective, TestValidateBeforeSubmitComponent],
                imports: [FormsModule],
                providers: [NgForm, HTMLButtonElement]
                }).createComponent(TestValidateBeforeSubmitComponent);

                const formElement = fixture.debugElement.children[0];
                form = formElement.injector.get(NgForm);

                fixture.detectChanges(); // initial binding
                });

                it('should allow submission of a valid form', async(() => {
                //arrange
                fixture.componentInstance.providedValue = 'Arbitrary content'; //valid value
                fixture.detectChanges();
                fixture.whenStable().then(() => {
                expect(form.valid).toBe(true, 'Test has been set up incorrectly, form should be valid.');

                //act
                const buttonElement = fixture.debugElement.children[0].children[1];
                const button = buttonElement.nativeElement;
                button.click();

                //assert
                expect(form.submitted).toBe(true, 'Clicking the submit button on a valid form should have submitted the form.');
                });
                }));

                it('should prevent submission of an invalid form', async(() => {
                //arrange
                fixture.componentInstance.providedValue = ''; //invalid value
                fixture.detectChanges();
                fixture.whenStable().then(() => {
                expect(form.valid).toBe(false, 'Test has been set up incorrectly, form should be invalid.');

                //act
                const buttonElement = fixture.debugElement.children[0].children[1];
                const button = buttonElement.nativeElement;
                button.click();

                //assert
                expect(form.submitted).toBe(false, 'The directive should prevent an invalid form from submitting when the submit button is clicked.');
                });
                }));
                });





                share|improve this answer













                Someone did post an answer which put me on the right lines, but they've sadly deleted their answer so I can't give them credit. They pointed out that directives should be tested using a dummy component which is defined within the test file. I have created a component whose template is a form with an input, and I have been able to test the behaviour of the directive by testing the component.



                This is my working test code:



                import { NgForm, FormsModule } from '@angular/forms';
                import { Component } from '@angular/core';
                import { ComponentFixture, TestBed, async } from '@angular/core/testing';
                import { ValidateBeforeSubmitDirective } from './validate-before-submit.directive';

                @Component({
                //The input on this form is required, so we can easily set the form validity by giving it an empty/non-empty string.
                template: `<form #testForm="ngForm">
                <input name="providedValue" [(ngModel)]="providedValue" type="text" required />
                <button type="submit" [appValidateBeforeSubmit]="testForm">Submit</button>
                </form>`
                })
                class TestValidateBeforeSubmitComponent {
                providedValue: string;
                }

                describe('ValidateBeforeSubmitDirective', () => {
                let form: NgForm;
                let fixture: ComponentFixture<TestValidateBeforeSubmitComponent>;

                beforeEach(() => {
                fixture = TestBed.configureTestingModule({
                declarations: [ValidateBeforeSubmitDirective, TestValidateBeforeSubmitComponent],
                imports: [FormsModule],
                providers: [NgForm, HTMLButtonElement]
                }).createComponent(TestValidateBeforeSubmitComponent);

                const formElement = fixture.debugElement.children[0];
                form = formElement.injector.get(NgForm);

                fixture.detectChanges(); // initial binding
                });

                it('should allow submission of a valid form', async(() => {
                //arrange
                fixture.componentInstance.providedValue = 'Arbitrary content'; //valid value
                fixture.detectChanges();
                fixture.whenStable().then(() => {
                expect(form.valid).toBe(true, 'Test has been set up incorrectly, form should be valid.');

                //act
                const buttonElement = fixture.debugElement.children[0].children[1];
                const button = buttonElement.nativeElement;
                button.click();

                //assert
                expect(form.submitted).toBe(true, 'Clicking the submit button on a valid form should have submitted the form.');
                });
                }));

                it('should prevent submission of an invalid form', async(() => {
                //arrange
                fixture.componentInstance.providedValue = ''; //invalid value
                fixture.detectChanges();
                fixture.whenStable().then(() => {
                expect(form.valid).toBe(false, 'Test has been set up incorrectly, form should be invalid.');

                //act
                const buttonElement = fixture.debugElement.children[0].children[1];
                const button = buttonElement.nativeElement;
                button.click();

                //assert
                expect(form.submitted).toBe(false, 'The directive should prevent an invalid form from submitting when the submit button is clicked.');
                });
                }));
                });






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 15 '18 at 17:50









                TimTim

                1,19921630




                1,19921630
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52876748%2funit-test-angular-directive-with-a-form%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python