天天看點

Angular jasmine fixture.detectChanges如何觸發directive的set方法

import { Component } from '@angular/core';

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

import { FocusDirective } from './focus.directive';

import { KeyboardFocusService } from './services';

import { By } from '@angular/platform-browser';

@Component({

 selector: 'cx-host',

 template: `

`,

})

class MockComponent {

 jerry = 1;

}

class MockKeyboardFocusService {

 get() {}

 set() {}

 shouldFocus() {}

 getPersistenceGroup() {}

 findFirstFocusable(){}

 hasPersistedFocus(){}

describe('FocusDirective', () => {

 let fixture: ComponentFixture;

 let component: MockComponent;

 beforeEach(

   waitForAsync(() => {

     TestBed.configureTestingModule({

       declarations: [FocusDirective, MockComponent],

       providers: [

         {

           provide: KeyboardFocusService,

           useClass: MockKeyboardFocusService,

         },

       ],

     }).compileComponents();

     fixture = TestBed.createComponent(MockComponent);

     component = fixture.componentInstance;

     fixture.detectChanges();

   })

 );

 it('should focus itself', () => {

   let service: KeyboardFocusService;

   service = TestBed.inject(KeyboardFocusService);

   const host = fixture.debugElement.query(By.css('#b'));

   const el = host.nativeElement;

   spyOn(service, 'findFirstFocusable').and.returnValue(el);

   spyOn(el, 'focus').and.callThrough();

   fixture.detectChanges();

   const event = {

     preventDefault: () => {},

     stopPropagation: () => {},

   };

   host.triggerEventHandler('focus', event);

   expect(el.focus).toHaveBeenCalled();

   expect(service.findFirstFocusable).toHaveBeenCalled();

   component.jerry = 2;

 });

});

Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法
Angular jasmine fixture.detectChanges如何觸發directive的set方法

繼續閱讀