0

I am trying to test method call when certain button is clicked, nothing seems to work.

This is the line in my HTML file:

<button class="btn-grey" (click)="methodTest()">ODUSTANI</button>

And method in my component:

export class MyComponent {

    constructor (public dialog: Matdialog) {}

    methodTest(): void {
        this.dialog.open(
            myOtherComponent,
            {disableClose: true, data:{title: someTitle, message: someMessage}
        );
    }

}
4
  • Please give the full code Commented Mar 26, 2018 at 13:04
  • I edited the original question. This is information I can provide. Commented Mar 26, 2018 at 13:31
  • Is there any error message on the console? Maybe you missed a } in your method. Commented Mar 26, 2018 at 14:14
  • The question is not about the method, it works just fine. I am trying to write unit test for that method call on click of a button. Commented Mar 26, 2018 at 15:25

1 Answer 1

1

You will need to set up the test using the Angular TestBed and inject the service.

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

describe('', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
       imports: [
         AppModule
       ],
       declarations: [ 
       ],
       providers: [
       ]}).compileComponents()
      .then(() => {
         fixture = TestBed.createComponent(TestComponent);
         comp = fixture.componentInstance;
      });
   }));
});

Then you need to spy on the onButtonClick method, click the button and check that whether the method was called

it('should', async(() => {
   spyOn(component, 'onButtonClick');

   let button = fixture.debugElement.nativeElement.querySelector('button');
   button.click();

   fixture.whenStable().then(() => {
   expect(component.onButtonClick).toHaveBeenCalled();
  })
}));
Sign up to request clarification or add additional context in comments.

1 Comment

that's verifying that the button is clicked on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.