Jest 无法读取未定义的属性“导入" [英] Jest cannot read property 'import' of undefined

查看:46
本文介绍了Jest 无法读取未定义的属性“导入"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以异步加载依赖项:

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()
  …
}

多亏了 Bergi,这一切正常,但 Jest 被 window.System.import 并给我错误 Cannot read property 'import' of undefined.我怎样才能正确地模拟这个?

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?

推荐答案

window 属性可以这样模拟:

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.

这篇关于Jest 无法读取未定义的属性“导入"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆