Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  50] [ 3]  / answers: 1 / hits: 11451  / 5 Years ago, fri, december 20, 2019, 12:00:00

I've got my Yarn package.json set up like this, where I create a global variable called localPath.



{
jest: {
globals: {
localPath: Users/alex/Git/mytodolist
}
}
}


Then, in one of my spec tests, I run



console.log(localPath)


but get this error.



ReferenceError: localPath is not defined

5 |
> 6 | console.log(localPath)


Does anyone know how to call the global variable you set up? I can only find articles on creating the variable, but not on how to call it.



Source: https://jestjs.io/docs/en/configuration#globals-object



Edit: Thanks to @slideshowp2 for the correct answer below. Turns out I didn't need to use a global variable in the end, as you can dynamically grab the execution path at run time. However, this will certainly be useful in the future.



beforeAll(async () => {
await page.goto('file:///'+process.cwd()+'/index.html')
})

More From » jestjs

 Answers
13

It should work. Here is a minimal working example:



./src/index.js:



export function sum(a, b) {
return a + b;
}


./src/__tests__/index.spec.js:



import { sum } from ../;

it(should sum, () => {
// eslint-disable-next-line
console.log(localPath: , localPath);
const actualValue = sum(1, 2);
expect(actualValue).toBe(3);
});


jest.config.js:



module.exports = {
preset: ts-jest/presets/js-with-ts,
testEnvironment: node,
coverageReporters: [json, text, lcov, clover],
testMatch: [**/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[jt]s?(x)],
globals: {
localPath: Users/alex/Git/mytodolist
}
};


Unit test result:



 PASS  src/__tests__/index.spec.js
✓ should sum (4ms)

console.log src/__tests__/index.spec.js:5
localPath: Users/alex/Git/mytodolist

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.233s
Ran all test suites.


As you can see, the value of global variable localPath has been set. Please print the global object and check in your tests.



Codesandbox: https://codesandbox.io/s/unruffled-feistel-byfcc


[#5269] Wednesday, December 18, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;