ค้นหาเว็บไซต์

ไม่สามารถรันทดสอบ jest บนแอปพลิเคชัน react native ของฉัน [React Native + TypeScript]


ฉันกำลังพยายามรันการทดสอบในโครงการนี้เป็นครั้งแรก แต่ฉันมีปัญหาบางอย่างกับโมดูล นี่คือข้อผิดพลาดที่ฉันพบ:

FAIL  src/components/text/index.test.tsx
  ● Test suite failed to run

    Cannot find module 'react' from 'src/components/text/index.test.tsx'

    > 1 | import React from 'react'
        | ^
      2 | import { render } from '@testing-library/react-native'
      3 | import { ZzText } from './index'
      4 | 

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:307:11)
      at Object.<anonymous> (src/components/text/index.test.tsx:1:1)

Test Suites: 2 failed, 2 total
Tests:       0 total
Snapshots:   0 total
Time:        1.346 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

และนี่คือไฟล์การตั้งค่า jest ของฉัน:

package.json
"jest": {
    "moduleFileExtensions": [
      "js",
      "jsx",
      "ts",
      "tsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  },
babel.config.json
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "declaration": true,
    "skipLibCheck": true
  },
  "exclude": [
    "node_modules",
    "babel.config.json",
    "metro.config.js",
    "jest.config.ts",
    "example"
  ],
  "include": ["src/**/*"]
}
jest.config.ts
import type { Config } from '@jest/types'

const config: Config.InitialOptions = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(ts|tsx|js|jsx)?$': 'babel-jest',
  },
  roots: ['<rootDir>/src'],
}

export default config

นี่คือการทดสอบที่ฉันกำลังพยายามทำ ฉันไม่แน่ใจว่ากำลังทำถูกต้องหรือไม่ ฉันกำลังเริ่มตอนนี้ด้วยการทดสอบ (นี่คือส่วนประกอบข้อความง่าย ๆ)

import React from 'react'
import { render } from '@testing-library/react-native'
import { ZzText } from './index'

describe('', () => {
  test('Should start with initial state', () => {
    const { getByTestId } = render(<ZzText testID='firstTest' />)
    const teste = getByTestId('firstTest')
    console.log(teste)
  })
})

บทความที่เกี่ยวข้อง