I am currently working on setting up the Jest testing framework and running a basic test (using an example from jestjs.io).
Here is the content of the sum.ts file:
function sum(a: any, b: any):any {
return a + b;
}
module.exports = sum;
And here is the content of the sum.test.ts file:
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
When I run the tests in the console, I encounter the following error message:
yarn test
yarn run v1.22.17
warning ../../../package.json: No license field
$ jest
FAIL src/sum.test.ts
● Test suite failed to run
src/sum.test.ts:1:7 - error TS2451: Cannot redeclare block-scoped variable 'sum'.
1 const sum = require('./sum');
~~~
src/sum.ts:1:10
1 function sum(a: any, b: any) {
~~~
'sum' was also declared here.
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.87 s
Ran all test suites.
error Command failed with exit code 1.
How can this issue be resolved?
One potential solution is to modify the import statement in the 'sum.test.ts' file as follows:
import { sum } from './sum'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Upon running the tests again, the console displays the following:
yarn test
yarn run v1.22.17
warning ../../../package.json: No license field
$ jest
FAIL src/sum.test.ts
● Test suite failed to run
src/sum.test.ts:1:21 - error TS2306: File '/Users/pasmo/Code/sandbox/.../src/sum.ts' is not a module.
1 import { sum } from './sum'
~~~~~~~
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.812 s
Ran all test suites.
error Command failed with exit code 1.
................