Skip to content

Commit a5babeb

Browse files
committed
add App.test.tsx test with react testing library
- enhance jest.config.js 1. add moduleDirectories: ['node_modules', 'src'], so jest can find modules in src folder instead of writing test like this: import greeter from './greeter' we can: import greeter from 'greeter'; 2. add setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'] to support extended handy expect check: testing-library/react-testing-library#379 (comment) - add "esModuleInterop": true in tsconfig.json to fix: Cannot read property 'createElement' of undefined using TypeScript testing-library/react-testing-library#374 (comment) esModuleInterop vs allowSyntheticDefaultImports note: Enabling esModuleInterop will also enable allowSyntheticDefaultImports. - add a new text example for react component: App.test.tsx
1 parent c6c0865 commit a5babeb

File tree

5 files changed

+15
-1
lines changed

5 files changed

+15
-1
lines changed

jest.config.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ module.exports = {
33
preset: 'ts-jest',
44
testEnvironment: 'jsdom',
55
roots: ['<rootDir>/src'],
6+
moduleDirectories: ['node_modules', 'src'],
67
transform: {
78
'^.+\\.(ts|tsx)$': 'ts-jest',
89
},
10+
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
911
testMatch: [
1012
'<rootDir>/src/**/__tests__/**/*.[jt]s?(x)',
1113
'<rootDir>/src/**/?(*.)+(spec|test).[jt]s?(x)',

src/App.test.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import App from 'App';
2+
import React from 'react';
3+
import { render, screen } from '@testing-library/react';
4+
5+
test('renders emotion button', () => {
6+
render(<App userName="test">test</App>);
7+
const emotionButton = screen.getByRole('button');
8+
expect(emotionButton).toHaveTextContent('hello, I am from emotion');
9+
});

src/greeter.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import greeter from './greeter';
1+
import greeter from 'greeter';
22

33
it('should pass', () => {
44
const result = greeter('Peggy');

src/setupTests.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// https://github.com/testing-library/react-testing-library/issues/379#issuecomment-618089505
2+
import '@testing-library/jest-dom/extend-expect';

tsconfig.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"allowJs": true,
44
"allowSyntheticDefaultImports": true,
55
"baseUrl": "src",
6+
"esModuleInterop": true,
67
"importsNotUsedAsValues": "preserve",
78
"jsx": "react",
89
"lib": ["ES2020", "DOM"],

0 commit comments

Comments
 (0)