【问题标题】:how to mock i18next module in jest如何开玩笑地模拟 i18next 模块
【发布时间】:2018-07-25 03:21:09
【问题描述】:

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

一切都已安装到位,但是当我导入组件时,我希望在 .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);
  });

});

谢谢。

【问题讨论】:

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


    【解决方案1】:

    错误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

    【讨论】:

    • jest.mock('i18next', () => ({ use: () => { return { init: () => { } }; }, t: k => k })); 这部分地得到了另一个错误消息:TypeError: this.i18next.on is not a function 38 | .init(i18nextOptions); 39 | > 40 | export default new VueI18Next(i18next); 41 |
    • 即使我在 init 中添加 on 和 t 函数,与我上面的评论相同的错误仍然存​​在。
    • 尝试将您的 i18n 配置传递给 shallow 方法,它应该是这样的:shallw(Home, i18n),我对这个问题给出了类似的答案:stackoverflow.com/a/48792562/1042324
    • 嗯...,我不确定。当我将它添加到浅/安装时,在我的 karma+jasmine 设置中它什么也不做,仍然说 i18next 没有定义。不过,在 Jest 中,它不会抱怨 i18next,而是会抛出一堆 ReferenceError: sessionStorage is not defined,错误。所以即使是基本的断言,比如:expect(2+2).toBe(4);不工作...
    猜你喜欢
    • 2017-12-14
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多