将 HTML 作为字符串导入并使用 Jest 进行测试

Import HTML as string and test with Jest

我正在使用 sveltekit,但无法使用文件 api 导入 html 模板。所以我决定通过编写一个模块来导入文档的内容作为字符串(描述here)。

// src/global.d.ts

/// <reference types="@sveltejs/kit" />
declare module '*.html' {
  const content: string
  export default content
}

到目前为止一切顺利,但现在我需要测试代码,jest 无法解释代码。

● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/home/developer/workspace/src/assets/html/confirm_email.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<!DOCTYPE html>
                                                                                  ^

SyntaxError: Unexpected token '<'

我不明白 jest 如何理解 .d.ts 文件...我如何才能测试代码?

你安装@babel/plugin-transform-runtime"吗?

我分享我的配置 jest/svelte-jester..

我有:

jsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "$lib": ["src/lib"],
            "$lib/*": ["src/lib/*"]
        }
    },
    "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"],
    
}

svelte.config.js

 import vercel from '@sveltejs/adapter-vercel'

/** @type {import('@sveltejs/kit').Config} */
const config = {
 
    kit: {
        adapter: vercel(),
        vite: {
            define: {
              'process.env': process.env,
            },
          },
     
     
    },
    transform: {
        "^.+\.svelte$": ["svelte-jester", { "preprocess": true }]
      }
};

export default config;

babel.config.json

{
  "presets": [
    ["@babel/preset-env", { "modules": "auto" }]
  ],
    "plugins": ["babel-plugin-transform-vite-meta-env","@babel/plugin-transform-runtime"]
}

jest.config.js

export default {
  "transform": {
    "^.+\.js$": "babel-jest",
   "^.+\.svelte$": "svelte-jester",
   
 },
 "moduleFileExtensions": ["svelte", "js"],
  "testEnvironment": "jsdom",
  "setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"]
 
 
  }

和整个package.json

{
  "name": "sveltekit",
  "version": "0.0.1",
  "scripts": {
    "dev": "svelte-kit dev",
    "build": "svelte-kit build",
    "package": "svelte-kit package",
    "preview": "svelte-kit preview",
    "test": "jest src",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/plugin-transform-modules-commonjs": "^7.16.8",
    "@babel/plugin-transform-runtime": "^7.17.0",
    "@babel/preset-env": "^7.16.11",
    "@supabase/supabase-js": "^1.29.1",
    "@sveltejs/adapter-auto": "^1.0.0-next.7",
    "@sveltejs/kit": "^1.0.0-next.215",
    "@sveltejs/svelte-virtual-list": "^3.0.1",
    "@testing-library/svelte": "^3.0.3",
    "autoprefixer": "^10.4.1",
    "babel-jest": "^27.4.6",
    "babel-plugin-transform-vite-meta-env": "^1.0.3",
    "jest": "^27.4.7",
    "postcss-load-config": "^3.1.1",
    "prettier": "^2.5.1",
    "prettier-plugin-svelte": "^2.5.1",
    "svelte": "^3.44.0",
    "svelte-jester": "^2.1.5",
    "svelte-lazy": "^1.0.12",
    "tailwindcss": "^3.0.8",
    "ts-jest": "^27.1.3"
  },
  "type": "module",
  "dependencies": {
    "@fontsource/fira-mono": "^4.5.0",
    "@lukeed/uuid": "^2.0.0",
    "@testing-library/jest-dom": "^5.16.1",
    "cookie": "^0.4.1",
    "svelte-lazy-image": "^0.2.0",
    "swiper": "^8.0.3"
  },
  "testEnvironment": "jsdom"
}

我希望它会有所帮助 you.I 在设置 jest 时也遇到了很多麻烦..

1.Import html 作为字符串

我用另一种方法解决了这个问题...

我正在使用 vite 资源将 html 文件作为资产导入,可以看到 here in the documentation

import confirm_email_template from '../../../assets/html/confirm_email.html?raw'

2.Test 使用 Jest

对于生产,它运行完美,但对于单元测试,代码会中断,因为 Jest 无法将资产作为模块导入。

因此问题的第二部分已使用资产模拟解决(我不知道这是否是最佳做法)。

// jest.config.cjs

{
⋮
  moduleNameMapper: {
      ⋮
      '([a-zA-Z_ ]+\.html)\?raw$': '<rootDir>/__mocks/.cjs'
  }
⋮
}

为了让它工作,我创建了以下文件夹结构:

__mocks
      |
       confirm_email.html.cjs
       another_asset_mocked.html.cjs

confirm_email.html.cjs 看起来像这样:

// __mocks/confirm_email.html.cjs
module.exports = '<html>content<html>'