首页 > 解决方案 > 由于 lodash 在 Vue 中使用 Jest 进行测试在子组件中失败

问题描述

在我的 Vue 应用程序中,lodash 作为 Vue 插件全局加载main.js

import _ from "lodash"

export default function install(Vue) {
    Vue.prototype._ = _
    Vue.mixin({
        computed: {
            _: () => _
        }
    })
}

然后,我有一个使用 lodash 函数的子组件,我正在尝试shallowMount它的父组件,但是当我运行测试时它失败并出现以下错误:

ReferenceError: _ is not defined

      270 |         },
    > 272 |         debouncedSearch: _.debounce(
          | ^
      273 |             function (value) {
      274 |                 this.currentQuery = value
      275 |                 if (!_.isEmpty(this.currentQuery)) {

我在这里缺少什么?

解决方案:

在查看标记为正确的 awnser 之后,我添加import debounce from "lodash/debounce"并替换_.debounce()debounce它,它工作正常。

标签: javascriptunit-testingvue.jsjestjs

解决方案


尝试像这样重写你的函数:

// Lodash is not defined out here
debouncedSearch: function() {
    // But is available in here
    return _.debounce(
        ...
    );
}

推荐阅读