Search code examples
angularjestjsangular-directive

Property 'toHaveStyle' does not exist on type 'JestMatchers<Element>'


I have a Color Directive which set background-color to card. I dont understand how to testing it by Jest

  @Input('appColor') public color: string;

  constructor(
    private element: ElementRef,
    private render: Renderer2,
  ) {
  }

  public ngAfterViewChecked(): void {
    this.setCategoryColor();
  }

  private setCategoryColor(): void {
    this.render.setStyle(this.element.nativeElement, 'background-color', this.color);
  }

test

 it('create testing html template and check set color', () => {
       instance.ngAfterViewChecked();

    expect(spectator.element).toHaveStyle({
      backgroundColor: 'red',
    });
  });

Solution

  • I solved the problem like this:

    directive

      public ngAfterViewInit(): void {
        this.setCategoryColor();
        this.changeDetector.detectChanges();
      }
    
      private setCategoryColor(): void {
        this.render.setStyle(this.element.nativeElement, 'background-color', this.color);
      }
    

    directive.spec.ts

    describe('UnsubscribeDirective', () => {
      let spectator: SpectatorDirective<ColorDirective>;
      let instance: ColorDirective;
    
      const createDirective = createDirectiveFactory({
        directive: ColorDirective,
        template: `<div appColor="#fff">Testing Highlight Directive</div>`,
      });
    
      beforeEach(() => {
        spectator = createDirective();
        instance = spectator.directive;
      });
    
      describe('should create directive', () => {
        it('should be defined', () => {
          expect(instance).toBeDefined();
        });
      });
    
      describe('ngAfterViewInit', () => {
        it('should be defined', () => {
          expect(instance.ngAfterViewInit).toBeDefined();
        });
      });
    
      it('set background-color', () => {
        instance.ngAfterViewInit();
    
        expect(spectator.element).toHaveStyle({
          backgroundColor: '#fff',
        });
      });
    });