unit-testing - Jest 单元测试问题 : "module not found"

标签 unit-testing jestjs nuxt.js ts-jest

目前 Jest 没有通过测试,因为它找不到组件内部调用的模块:

 FAIL  tests/Unit/VHeaderBar.spec.ts
  ● Test suite failed to run

    Cannot find module '@@/public/assets/images/placeholder.png' from 'VHeaderBar.vue'



      at Resolver.resolveModule (node_modules/jest-runtime/node_modules/jest-resolve/build/index.js:221:17)
      at src/components/VHeaderBar.vue:687:18
      at Object.<anonymous> (src/components/VHeaderBar.vue:749:3)

案例

NuxtJs中,@@符号指的是root目录,因为最终的解决方案是我们要将图片存放在public文件夹中或存储文件夹,位于项目的根目录中。

运行测试时 jest 检查 src 文件夹,然后尝试挂载从根目录存储的图像,但找不到它们。

我尝试了很多不同的方法来解决这个问题,但似乎找不到解决方案。 这是我已经尝试过的候选 list :

  • 更改 regex 以检查图像文件并使用 Jest 配置文件中的 moduleNameMapper 选项将其引导至正确的文件夹。
  • 我在 Stack 上读到一些关于使用“模拟”文件夹的信息,该文件夹通过 javascript 导出图像文件,但这没有用。
  • 在 Jest 配置文件中使用 modulePaths 选项。
  • tsconfig.js 中为 assets 文件夹创建一个别名,并在 moduleNameMapper 中使用它
  • 在 VueJS 组件和测试文件中尝试了一种不同的方法来加载 Assets ,这破坏了编译过程(所以我恢复了它)。

当前 Jest 配置文件

module.exports = {
    moduleFileExtensions: [
        "ts",
        "tsx",
        "vue",
        "js",
        "json"
    ],
    watchman: false,
    moduleNameMapper: {
        "/\.(gif|jpg|jpeg|tiff|png)$/i": "<rootDir>/public/assets/images/$1",
        "^@/(.*)$": "<rootDir>/src/$1",
        "^~/(.*)$": "<rootDir>/src/$1",
        "^~~/(.*)$": "<rootDir>/src/$1"
    },
    transform: {
        // process js with `babel-jest`
        "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
        // process `*.vue` files with `vue-jest`
        ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
        // process `*.ts` files with `ts-jest`
        "^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest",
    },
    snapshotSerializers: [
        "<rootDir>/node_modules/jest-serializer-vue"
    ],
    collectCoverage: true,
    collectCoverageFrom: [
        "<rootDir>/src/components/**/*.vue",
        "<rootDir>/src/pages/**/*.vue",
        "<rootDir>/src/layouts/**/*.vue"
    ],
    testMatch: [
        '**/tests/Unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
    ],
}

当前文件夹结构(仅我们用于测试的文件夹)

project folder
- public
-- assets
--- **images**

- src
-- components
--- **mounted component** (works)

- tests
-- Unit
--- mountedComponent.spec.ts

有什么建议吗?

我是否修复了 jest.config

语法有问题吗?

我必须修复 tsconfig 吗?

最佳答案

我遇到过类似的问题,归结为 typescript 无法导入该文件。

我通过将文件类型定义添加到 files.d.ts 解决了这个问题:

declare module "*.pdf" {
  const file: Buffer;
  export default file;
}

declare module "*.jpeg" {
  const src: string;
  export default src;
}

declare module "*.png" {
  const src: string;
  export default src;
}

tsconfig.json 中引用此文件:

{
  "compilerOptions": {
    /* ... */
  },
  "files": ["./src/@types/files.d.ts"],
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

并将文件转换添加到 jest.config.js:

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["<rootDir>/src/"],

  moduleNameMapper: {
    "@app/(.*)": "<rootDir>/src/$1",
    "@lib/(.*)": "<rootDir>/src/lib/$1",
  },
  transform: { // Transforms here
    "\\.(gql|graphql)$": "@jagi/jest-transform-graphql",
    "\\.(html|html|txt|pem|key)$": "./jest-transform-text.js",
    "\\.(p12|pdf|otf|ttf)$": "./jest-transform-buffer.js",
    "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"

  },
  coverageReporters: ["text", "lcov"],
};

转换文件示例:

// jest-transform-buffer.js

"use strict";
const fs = require("fs");
module.exports = {
  process(src, filename) {
    const data = fs.readFileSync(filename, "hex");
    return (
      'module.exports=Buffer.from("' +
      data +
      '","hex");module.exports.default=module.exports;'
    );
  },
};

对于来自 create react app 的图像(或其他您只需要文件名的文件):

'use strict';

const path = require('path');
const camelcase = require('camelcase');

// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html

module.exports = {
  process(src, filename) {
    const assetFilename = JSON.stringify(path.basename(filename));

    if (filename.match(/\.svg$/)) {
      // Based on how SVGR generates a component name:
      // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
      const pascalCaseFilename = camelcase(path.parse(filename).name, {
        pascalCase: true,
      });
      const componentName = `Svg${pascalCaseFilename}`;
      return `const React = require('react');
      module.exports = {
        __esModule: true,
        default: ${assetFilename},
        ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
          return {
            $$typeof: Symbol.for('react.element'),
            type: 'svg',
            ref: ref,
            key: null,
            props: Object.assign({}, props, {
              children: ${assetFilename}
            })
          };
        }),
      };`;
    }

    return `module.exports = ${assetFilename};`;
  },
};

关于unit-testing - Jest 单元测试问题 : "module not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58838279/

相关文章:

javascript - Vue/Nuxt - 在客户端中通过 id 获取元素在加载时返回 null,但在重新加载时有效

css - NuxtJS css 提取如何用于生成的静态网站?

vue.js - nuxt watchQuery 无法使用新查询更新路由

unit-testing - Yii2 ActiveRecord 用 Mockery 进行模拟

c++ - 如何让 STL 抛出异常而不是断言?

android - Jest testing::测试失败并且错误路由到\react-native-vector-icons

java - 使用 Spring,@InjectMock 注释测试目标不使用模拟

javascript - 使用 enzyme 测试 React Native FlatList

javascript - 单元测试包含带有插槽的 Vuetify 数据表的 Vue 组件

javascript - 如何测试抛出异常?