簡體   English   中英

如何在 Angular 中模擬自定義對話框以使用 Jest 進行單元測試

[英]How to mock Custom Dialog in Angular for Unit Testing using Jest

我正在為從localStorage檢索到的在isEdit = 'true'上打開對話框組件的方法編寫單元測試和代碼覆蓋率的測試用例。

這里的問題是在第一個測試用例中,我設置isEdit = true並調用方法showMessagesList() ,然后 if 內的行被代碼覆蓋但測試用例失敗並出現異常Cannot read property 'openModalDialog' of undefined 但是第二個測試用例並沒有失敗,因為我正在監視它。 誰能幫我mocking Jest中的Dialog組件以及它如何消除錯誤

異常 SideBarDrawerComponent › 應在 true 時調用 show Message Items

    TypeError: Cannot read property 'openModalDialog' of undefined

      49 |     this.isEdit = localStorage.getItem('isEditMode').toString()
      50 |     if (this.isEdit === 'true') {
    > 51 |       this.modalDialog.openModalDialog()
         |                                ^
      52 |     } else {
      53 |       this.toggleComponent.emit(componentTypes.LIST)
      54 |     }

組件方法

showMessagesList() {
    // Check if the compose componenet is in edit mode;
    this.isEdit = localStorage.getItem('isEdit').toString()
    if (this.isEdit === 'true') {
      this.modalDialog.openModalDialog() // exception when isEdit is set to 'true' in the test case
    } else {
      this.toggleComponent.emit("true")
    }
  }

Spect.ts 文件

import { ComponentFixture, TestBed } from '@angular/core/testing'
import { By } from '@angular/platform-browser'
import {
  ModalDialogComponent,
  ModalDialogModule,
} from 'modal-dialog'

import { ContentModel } from '../../model/content.model'
import * as componentTypes from '../componentTypes'
import { ComposeComponent } from '../compose-message/compose.component'
import { MessageItemsComponent } from '../message-list/message-item.component'
import { SideBarDrawerComponent } from './side-bar-drawer.component'
import spyOn = jest.spyOn


window.ResizeObserver =
  window.ResizeObserver ||
  jest.fn().mockImplementation(() => ({
    disconnect: jest.fn(),
    observe: jest.fn(),
    unobserve: jest.fn(),
  }))

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [ModalDialogModule],
      declarations: [
        SideBarDrawerComponent,
        MessageItemsComponent ,
        ComposeComponent,
        ModalDialogComponent, // <-- Dialog Component
      ],
      providers: [
        { provide: Window, useValue: window },
        { provide: ModalDialogComponent, useValue: {} },
      ],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(SideBarDrawerComponent)
        component = fixture.componentInstance
      })
  })

  beforeEach(() => {
    component.content = mockContent
  })

  it('should call show Message Items when true', () => {
    localStorage.setItem('isEditMode', 'true')
    component.showMessagesList()
    component.isEdit = localStorage.getItem('isEditMode') ?? ''
    fixture.detectChanges()
    expect(component.isEdit).toBe('true')
  })

  it('should check open dialog', () => {
    const isEdit = 'true'
    component.isEdit = isEdit.toString()
    expect(component.isEdit).toBe('true')
    jest.spyOn(component, 'showMessagesList').mockImplementationOnce(() => {
      if (isEdit === 'true') {
        expect(component.modalDialog.openModalDialog).toBeCalled()
      }
    })
  })
})

可能是錯字問題,但我可以在這里看到一個問題:

this.exampleModalDialog4.openModalDialog()
// --------------------^-----4 added here.

然而,您可以為 Modal 對話框提供一些模擬方法實現:

{ 
  provide: ModalDialogComponent, 
  useValue: {
     openModalDialog: () => {},
     // other implementations
  } 
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM