Global Variable in Jest Unit Test

I am new to Jest and am trying to write some unit tests for my existing React application. I have a global window.CONFIG variable that stores some configurations that are used in different places of the application. This variable is initialized in the script tag to host the HTML page.

Now I'm trying to write a test of an auxiliary function, which depends on this window.CONFIG and is always undefined when accessing

Here is the code:

config.js

 export default window.CONFIG; 

application / 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 always undefined. Since the browser landing page is not loaded, window.CONFIG not initialized. How can I mock this config module in my unit test in Jest?

Thanks in advance!

+5
source share
2 answers

I'm not sure if this will help you or not, but you can put global variables directly in package.json

 "jest":{ "globals": { "config": {"foo":"bar"} } } 
+2
source

I solved this by creating a manual config.js layout in the config.js directory as follows:

 let configMock = jest.genMockFromModule('../config'); let __mockConfig = {}; __mockConfig.baseUrl = "test_base_url/"; configMock = __mockConfig; export default configMock; 
0
source

Source: https://habr.com/ru/post/1243196/


All Articles