Jest cannot read property 'import' of undefined

雨燕双飞 提交于 2021-01-29 20:40:23

问题


I have the following code to load a dependency asynchronously:

declare global {
  interface Window {
    System: System.Module
  }
}

const fooService = window.System.import('@internal/foo-service').then(module => module.FooService)
//                              ^ Jest trips up here

async function func1() {
  (await fooService).doBar()
  …
}

async function func2() {
  (await fooService).doBar2()
  …
}

This works fine thanks to Bergi but Jest is tripping up over window.System.import and gives me the error Cannot read property 'import' of undefined. How can I properly mock this?


回答1:


The window property can be mocked like that:

import { System } from 'systemjs'

Object.defineProperty(window, 'System', { value: System })

For some reason I can't explain, this needs to happen before the import (!) of the component that is being tested.



来源:https://stackoverflow.com/questions/65609648/jest-cannot-read-property-import-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!