unit-testing - 如何在 Jest 中模拟 i18next 模块

标签 unit-testing vue.js vuejs2 jestjs vue-test-utils

我正在为现有的 Vue 项目设置测试环境,我决定用 vue-test-utils 开个 Jest 。

一切都已安装并就位,但是当我导入组件时,我希望在 .test.js 文件中进行测试,并添加组件以测试实用程序,如下所示:

let wrapper = shallow(Home)

测试套件因错误而崩溃:TypeError: Cannot read property 'i18next' of undefined

我决定模拟 i18next 模块,但我在模拟方面遇到了问题。我的模拟看起来像这样:

jest.mock('i18next', () => ({
  init: () => {},
  use: () => {},
  t: k => k
}));

但我总是得到错误:

TypeError: Cannot read property 'init' of undefined

      35 |
      36 | i18next
    > 37 |      .use(Locize)
      38 |      .init(i18nextOptions);
      39 |
      40 | export default new VueI18Next(i18next);

能否以某种方式解释模拟 i18next 模块以便我的包装器对象可以初始化的正确方法?另外,如果我做错了什么,请指出正确的方向。下面是完整的测试用例:

import { shallow, mount, createLocalVue } from '@vue/test-utils';
import Home from '../../src/app/pages/home/index/index.vue';

jest.mock('i18next', () => ({
  init: () => {},
  use: () => {},
  t: k => k
}));

describe('Home Component', () => {

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(Home);
  });

  it('something', () => {
    console.log('bleh');
    expect(wrapper.contains('div')).toBe(true);
  });

});

谢谢。

最佳答案

错误 Cannot read property 'init' of undefined 发生在 i18next.use(Locize) 的结果上,而不是 i18next目的。尝试将您的模拟更新为:

jest.mock('i18next', () => ({
  use: () => {
    init: () => {
      t: k => k,
      on: () => {}
    }
  }
}));

我用这个文件作为这个模拟的引用:panter/vue-i18next/src/i18n.js

关于unit-testing - 如何在 Jest 中模拟 i18next 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48789110/

相关文章:

c - 对带有 -Wl,--wrap 的包装函数的 undefined reference

vue.js - 是否可以从页面调用nuxt中的组件方法?

vue.js - 在 VueJs 应用程序中实现表情符号

javascript - 如何在 Vue v-if 中使用异步函数?

unit-testing - TDD 多线程应用程序

unit-testing - Golang 单元测试中的 stub 方法

javascript - 使用 Vuejs 搜索过滤器

javascript - 在 Vue 组件中使用 Controller 数据

javascript - Vue 模板或渲染函数尚未定义,但我两者都没有使用?

python - 使用 py.test 以编程方式收集或创建测试