由于lodash,在Vue中使用Jest进行测试导致子组件失败

时间:2019-11-23 12:54:03

标签: javascript unit-testing vue.js jestjs

在我的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)) {

我在这里想念的是什么?

解决方案:

查看标记为正确的遮篷后,我添加了import debounce from "lodash/debounce"并将_.debounce()替换为debounce,并且有效。

1 个答案:

答案 0 :(得分:0)

尝试像这样重新编写函数:

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