Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - Jest cannot read property 'import' of undefined

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...