开玩笑测试 Vue 单文件组件与离子电容器插件导入



GitHub 存储库的问题。

我正在使用 Vue 和 Capacitor 构建一个 Ionic 应用程序。我正在使用 vue-test-utils + Jest 设置单元测试。Jest 单元测试在尝试将电容器插件导入 Vue 单文件组件时失败。

Vue 应用程序是使用 Vue CLI 3 (v3.4.0) 创建的。CLI 选项包括使用 Jest 进行单元测试。我完全是单元测试的新手。在导入 Vue 组件之前,我天真地尝试过模拟 @capacitor/核心模块;这无济于事。

jest.config.js (Vue CLI 默认)

module.exports = {
moduleFileExtensions: ["js", "jsx", "json", "vue"],
transform: {
"^.+\.vue$": "vue-jest",
".+\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$":
"jest-transform-stub",
"^.+\.jsx?$": "babel-jest"
},
transformIgnorePatterns: ["/node_modules/"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1"
},
snapshotSerializers: ["jest-serializer-vue"],
testMatch: [
"**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
],
testURL: "http://localhost/",
watchPlugins: [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
};

MyComponent.vue

<template>...</template>
<script>
import { Plugins } from '@capacitor/core'
const { Filesystem } = Plugins
...
</script>

MyComponent.spec.js

import { shallowMount } from "@vue/test-utils";
import Component from "@/components/MyComponent.vue";
...

我希望测试可以毫无问题地运行。相反,当 Jest 尝试导入规范文件第 2 行的组件时,我收到以下错误消息:

TypeError: Cannot destructure property `Filesystem` of 'undefined' or 'null'.
35 | <script>
36 | import { Plugins } from '@capacitor/core'
> 37 | const { Filesystem } = Plugins

Plugins在第 36 行上未定义,因此第 37 行在试图从中解构Filesystem时会抱怨。

但是,在浏览器中,Filesystem对象如下所示:

{
"config": {
"name": "Filesystem",
"platforms": ["web"]
},
"loaded": false,
"listeners": {}, 
"windowListeners":{},
"DEFAULT_DIRECTORY": "DATA",
"DB_VERSION": 1,
"DB_NAME": "Disc",
"_writeCmds": ["add","put","delete"]
}

我不知道问题出在哪里。我不知道我是否应该对 Jest 做一些不同的事情,我不知道我是否不应该像我在某些例子中看到的那样直接在 Vue SFC 中导入电容器插件,或者......🤷 ♂️ .

编辑

虽然这让测试过去了,但将 @capacitor/core 包升级到 v1.1.0(几个小时前发布)也解决了这个问题。


按照关于模拟 Node 模块(特别是作用域模块)的 Jest 文档,我在 root 下创建了一个__mocks__文件夹,在其下创建了一个名为@capacitor的目录,并在名为core.js的文件下创建了一个文件。所以我最终得到了一个这样的结构:

.
├─__mocks__
│ └─ @capacitor
│    └─ core.js

core.js里面,我导出了我正在测试的 Vue 组件导入的部分(目前只有PluginsPlugins.Filesystem):

// core.js
module.exports = {
Plugins: {
Filesystem: {}
}
}

有了这些,Jest测试以飞行的绿色通过。

根据@jcesarmobile对 OP 的评论,将 @capacitor/core 从 1.0.0 版更新到 1.1.0 完全解决了这个问题。

修复:使电容器与 commonjs 兼容