【问题标题】:Lodash is undefined when testing a Svelte app with Jest使用 Jest 测试 Svelte 应用程序时 Lodash 未定义
【发布时间】:2021-02-15 18:13:01
【问题描述】:

我正在尝试使用 Jest 来测试我的 Svelte 项目,我读到的所有内容都表明我需要包含 svelte-jester 才能将我的 Svelte 代码转换为 Jest 可以处理的东西(我认为是 CommonJS?)。这似乎工作正常,除了我将 Lodash 导入到我的一些 Svelte 组件中,但 Jest 在运行其测试时报告 Lodash 未定义。 (在浏览器环境中,一切似乎都按预期工作。)

为了演示这个问题,我从 testing-library 网站复制并稍微修改了一个示例:

// Comp.svelte

<script>
  import _ from 'lodash';

  export let name
</script>

<h1>Hello {_.toUpper(name)}!</h1>

然后我的测试文件是

// tests/Comp.test.js

import '@testing-library/jest-dom/extend-expect'

import { render } from '@testing-library/svelte'

import Comp from '../Comp'

test('shows proper heading when rendered', () => {
  const { getByText } = render(Comp, { name: 'World' })

  expect(getByText('Hello WORLD!')).toBeInTheDocument()
})

我的 package.json 的相关部分如下,我也是从 testing-library 网站获得的。

{
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/preset-env": "^7.12.16",
    "@rollup/plugin-commonjs": "^16.0.0",
    "@rollup/plugin-node-resolve": "^10.0.0",
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/svelte": "^3.0.3",
    "babel-jest": "^26.6.3",
    "jest": "^26.6.3",
    "rollup": "^2.3.4",
    "rollup-plugin-svelte": "^7.0.0",
    "svelte": "^3.0.0",
    "svelte-jester": "^1.3.0"
  },
  "dependencies": {
    "lodash": "^4.17.20",
  },
  "jest": {
    "transform": {
      "^.+\\.js$": "babel-jest",
      "^.+\\.svelte$": ["svelte-jester", { "debug": true }]
    },
    "moduleFileExtensions": [
      "js",
      "svelte"
    ],
  }
}

测试输出表明,在Comp.svelte的编译版本中,Lodash是未定义的:

    TypeError: Cannot read property 'toUpper' of undefined

      5 | </script>
      6 |
    > 7 | <h1>Hello {_.toUpper(name)}!</h1>
        |              ^

      at create_fragment (src/Comp.svelte:7:14)
      at init (node_modules/svelte/internal/index.js:1489:37)
      at new Comp (src/Comp.svelte:83:3)
      at render (node_modules/@testing-library/svelte/dist/pure.js:81:21)
      at Object.<anonymous> (src/tests/Comp.spec.js:9:25)

组件的编译版本似乎表明,Lodash 至少在构建中是 require-d。

/* Comp.svelte generated by Svelte v3.31.0 */
"use strict";

const { SvelteComponentDev, add_location, append_dev, detach_dev, dispatch_dev, element, flush, init, insert_dev, noop, safe_not_equal, set_data_dev, text, validate_slots } = require("svelte/internal");
const { default: _ } = require("lodash");
const file = "Comp.svelte";

// etc.

谁能告诉我我需要做什么才能让 Lodash 正确导出和/或需要构建以进行 Jest 测试?非常感谢。

【问题讨论】:

    标签: jestjs lodash es6-modules svelte


    【解决方案1】:

    你可以查看这个issue

    它是未定义的,因为它是一个 CommonJS 模块 module.exports = x 并且您将它作为 ES 模块导入。如果你确实 import * as get from 'lodash/get' 它会起作用。

    【讨论】:

      猜你喜欢
      • 2016-12-14
      • 2018-11-04
      • 2021-08-02
      • 1970-01-01
      • 2020-07-13
      • 2016-09-14
      • 2019-01-16
      • 2021-11-30
      • 2018-05-29
      相关资源
      最近更新 更多