I am trying to write a test to my React component, using TypeScript, Jest as my test runner and Enzyme for testing my React components. Whenever I pass my component into the shallow
Enzyme function, I get the ts error "'Navbar' refers to a value, but is being used as a type here.", and underneath I get eslint error "Parsing error: '>' expected".
I tried it on some other components, all have the same error when being passed into the shallow
function as arguments. I suspect it may have something to do with my TS configurations, but for the life of me I cannot seem to be finding a solution.
Here's the code for Navbar.tsx:
import React from 'react';
import { shallow } from 'enzyme';
import Navbar from './Navbar';
describe('Navbar component', () => {
let component;
beforeEach(() => {
component = shallow(<Navbar />); // Error being desplayed here
});
it('should render without errors', () => {
expect(component).toMatchInlineSnapshot();
expect(component.length).toBe(1);
expect(component).toBeTruthy();
});
});
Also posting my config files:
tsconfig:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"]
}
jest.config.ts:
module.exports = {
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
snapshotSerializers: ['enzyme-to-json/serializer'],
setupTestFrameworkScriptFile: '<rootDir>/src/setupEnzyme.ts',
};
Enzyme setup:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';
configure({ adapter: new Adapter(), disableLifecycleMethods:
Have you tried to change the name of the file?
MyComponent.test.tsx
Also, did you install the types of jest and stuff
npm i -D @types/jest
.
I mean I’m saying this because if you look at the jest config where it says testRegex. You have it like this
__tests__/*.(test|spec).txs
the test must be inside a tests folder and it has to have the name: MyComponent.test
.tsx
First npm install -D @types/jest
& and write the test files as
fileName.test.tsx
My mistake was I was writing all the test files as fileName.test.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With