如何将玩笑依赖模拟提升到实际依赖?

时间:2019-03-18 13:12:08

标签: react-native mocking jestjs es6-class

我正在测试一个反应本机组件,该组件可以导入类LanguageStore。当前测试失败,因为该组件正在实例化此类,该类调用在测试范围内未定义的私有setter:

FAIL  src\modules\languageProvider\__tests__\LanguageProvider-test.js
  ● renders correctly

    TypeError: _this.strings.setLanguage is not a function

      at LanguageStore.setLanguage (src\modules\languageProvider\LanguageStore.js:25:15)
      at new LanguageProvider (src\modules\languageProvider\LanguageProvider.js:30:16)

问题:

如何将玩笑依赖性模拟置于实际依赖性之上?

为了解决这个问题,我根据此答案How can I mock an ES6 module import using Jest?呼叫了jest.mock。但是我得到了与以前相同的错误,因为测试正在调用LanguageStore的实现,而不是我在下面创建的模拟-_this.strings.setLanguage is not a function

import { View } from 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';
import connect from '../connect.js';
import LanguageProvider from '../LanguageProvider';
import LanguageStore from '../LanguageStore';

it('renders correctly', () => {

  const TestComponent = connect(Test);
  const strings = { test: 'Test' };
  const language = "en"

  const stringsMock = {
    setLanguage: jest.fn()
  };

  const mockSetLanguage = jest.fn();
  jest.mock('../LanguageStore', () => () => ({
    language: language,
    strings: stringsMock,
    setLanguage: mockSetLanguage,
  }));

  const wrapper = shallow(<LanguageProvider strings={strings} language="en"><Test /></LanguageProvider>);

  expect(wrapper.get(0)).toMatchSnapshot();

});


class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <View />;
  }
}

这是测试以及相关组件和类的链接:

https://github.com/BrianJVarley/react-native-prototyping/blob/i18nProvider-feature/src/modules/languageProvider/tests/LanguageProvider-test.js

1 个答案:

答案 0 :(得分:1)

Calling jest.mock within a test doesn't work

您需要将模拟移到测试之外,并确保工厂函数没有任何外部依赖项。

类似这样的东西:

import { View } from 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import connect from '../connect.js';
import LanguageProvider from '../LanguageProvider';
import LanguageStore from '../LanguageStore';

jest.mock('../LanguageStore', () => {
  const language = "en"
  const stringsMock = {
    setLanguage: jest.fn()
  };
  const mockSetLanguage = jest.fn();

  return () => ({
    language,
    strings: stringsMock,
    setLanguage: mockSetLanguage,
  })
});

it('renders correctly', () => {
  const TestComponent = connect(Test);
  const strings = { test: 'Test' };
  const wrapper = shallow(<LanguageProvider strings={strings} language="en"><Test /></LanguageProvider>);
  expect(wrapper.get(0)).toMatchSnapshot();
});


class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <View />;
  }
}