Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Jest Unit Test

I am new to Jest and trying to write some unit tests for my existing React App. I have a global variable window.CONFIG which stores some configurations which are used at different places in app. This variable is initialised in a script tag of landing HTML page

Now I am trying to write a test of an helper function which depends on this window.CONFIG and it is always undefined when accesses

Here is the code:

config.js

export default window.CONFIG;

app/helper.js

import config from "../config";

export default  {
  getCompanyURL(company) {
    return config.baseUrl + "/companies/" + company.id;
  },
}

_ tests _/helpers-test.js

jest.dontMock('../app/helpers.js');

var helper = require('../app/helpers.js').default;

describe('Get company URL', function() {

 it('returns company url with company id appended', function() {
   expect(companies.getCompanyURL({id:     1})).toBe('test_base_url/companies/1');
 });
});

config for Get Company Url is always undefined. As the browser landing page is not loaded window.CONFIG is not initialised. How can I mock this config module in my unit test in Jest?

Thanks in advance!!

like image 452
Yashika Garg Avatar asked Feb 17 '16 07:02

Yashika Garg


1 Answers

I'm not sure if this helps you or not but you can put global variables directly into your package.json

"jest":{
  "globals": {
    "config": {"foo":"bar"}
  }
}
like image 128
Falantar Avatar answered Dec 25 '22 17:12

Falantar