mardi 21 novembre 2017

Jest mock global variable's method

In my application I have a global variable in an external file

const Translate = {
  trans: () => {... some code}
}

and I use it in my React component

const title = Translate.trans('title');

and in my Component.test.js

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import Adapter from 'enzyme-adapter-react-16';
import Component from '../Component';
Enzyme.configure({ adapter: new Adapter() });

describe('Component Snapshot Tests', () => {
  it('renders default Component correctly', () => {
    const wrapper = shallow(<Component />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

afterEach(() => {
  global.Translator.trans = jest.fn(() => 'test text');
});

I get an error "TypeError: Translator.trans is not a function"

Jest settings

"jest": {
    "verbose": true,
    "rootDir": "./src",
    "globals": {
      "Translator": true
    }
  }

How better mock global variables in jest? Thanks!

Aucun commentaire:

Enregistrer un commentaire