如何使用 @host() 和条件参数单元测试 Angular 指令。

huangapple go评论67阅读模式
英文:

How to unit test angular directive with @host() and conditional parameter

问题

我有一个指令,在输入控件上调用 forceErrorStateUpdate 方法。如何对以下代码进行单元测试以实现完整的代码覆盖率?我的问题是,我无法对在 onInit 中调用的 ```this._textInput?.forceErrorStateUpdate();``` 进行完整的代码覆盖。

以下是单元测试代码。代码覆盖率大约为 75%。

describe('TestDirective', () => {
  // ... (其他测试内容)
  
  it('should invoke forceErrorUpdate on input component', () => {
    directiveInstance.ngOnInit();
    expect(directiveInstance.ngOnInit).toBeDefined();
  });
});
英文:

I have a directive which call forceErrorStateUpdate method on input control. how to unit test below code to achieve full code coverage? the problem I have is that I am not able to get full code coverage for the line this._textInput?.forceErrorStateUpdate(); which is called in onInit.

import { Directive, Host. OnInit, Optional } from '@angular/core';

@Directive({
  selector: '[showValidationError]'
});

export class TestDirective implements onInit {

  constructor(@Host() @Optional() private _textInput: any) { }

  ngOnInit(): void {
    this._textInput?.forceErrorStateUpdate();
  }

}

Below is the unit test code. the code coverage is around 75%.

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TestComponent } from '../test/test.component';
import { TestDirective } from './test.directive';

describe('TestDirective', () => {
  let testComponent: TestComponent;
  let testFixture: ComponentFixture<TestComponent>;
  let directiveInstance: TestDirective;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [TestComponent, TestDirective]
    }).compileComponents();
  });

  beforeEach(() => {
    testFixture = TestBed.createComponent(TestComponent);
    testComponent = testFixture.componentInstance;
    testFixture.detectChanges();
    const directiveEl = testFixture.debugElement.query(By.directive(TestDirective));
    expect(directiveEl).not.toBeNull();
    directiveInstance = directiveEl.injector.get(TestDirective);
  });
  
  it('should create', () => {
    expect(directiveInstance).toBeTruthy();
  });

  it('should have ngOnInit', () => {
    expect(directiveInstance.ngOnInit).toBeDefined();
  });

  it('should invoke forceErrorUpdate on input component', () => {
    directiveInstance.ngOnInit();
    expect(directiveInstance.ngOnInit).toBeDefined();
  });
});

答案1

得分: 3

如果要检查条件参数,可以这样操作:

beforeEach(() => {
    directive = new TestDirective(null);
});
  
it('如果未提供 _textInput,不应抛出错误', () => {
    directive['_textInput'] = null;
    expect(() => directive.ngOnInit()).not.toThrow();
});
  
it('在输入初始化时应调用 forceErrorStateUpdate()', () => {
    const mockInput = { forceErrorStateUpdate: jest.fn() };
    directive['_textInput'] = mockInput;
    directive.ngOnInit();
    expect(mockInput.forceErrorStateUpdate).toHaveBeenCalled();
});
英文:

If you want to check that conditional parameter you could like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

beforeEach(() =&gt; {
    directive = new TestDirective(null);
  });
  
  it(&#39;should not throw an error if _textInput is not provided&#39;, () =&gt; {
    directive[&#39;_textInput&#39;] = null;
    expect(() =&gt; directive.ngOnInit()).not.toThrow();
  });
  
   it(&#39;should call forceErrorStateUpdate() on input initialization&#39;, () =&gt; {
    const mockInput = { forceErrorStateUpdate: jest.fn() };
    directive[&#39;_textInput&#39;] = mockInput;
    directive.ngOnInit();
    expect(mockInput.forceErrorStateUpdate).toHaveBeenCalled();
  });

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月16日 16:37:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定