testing-library / native-testing-library

🐳 Simple and complete React Native testing utilities that encourage good testing practices.
https://native-testing-library.com
MIT License
515 stars 44 forks source link

"getByText" doesn't work #63

Closed san-smith closed 4 years ago

san-smith commented 4 years ago

Relevant code or config:

it('not work', () => {
    const { getByText } = render(<Text>About ℹ</Text>)
    getByText(/about/i)
})

What you did:

I just use example from docs

What happened:

  ● ErrorMessage › not work

    TypeError: Cannot read property 'includes' of undefined

      24 |   it('not work', () => {
      25 |     const { getByText } = render(<Text>About ℹ</Text>)
    > 26 |     getByText(/about/i)
         |     ^
      27 |   })
      28 | })
      29 | 

      at validComponentFilter (node_modules/@testing-library/react-native/dist/lib/query-helpers.js:37:43)
      at node_modules/@testing-library/react-native/dist/lib/queries/text.js:32:47
      at overrideCb (node_modules/@testing-library/react-native/dist/lib/query-helpers.js:75:22)
      at _findAll (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13002:7)
      at Proxy.findAll (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12931:12)
      at Proxy.<anonymous> (node_modules/@testing-library/react-native/dist/lib/query-helpers.js:78:24)
      at queryAllByText (node_modules/@testing-library/react-native/dist/lib/queries/text.js:31:31)
      at node_modules/@testing-library/react-native/dist/lib/query-helpers.js:172:24
      at node_modules/@testing-library/react-native/dist/lib/query-helpers.js:156:24
      at Object.it (app/auth/__tests__/ErrorMessage.test.tsx:26:5)

Reproduction:

Just use example from docs

Problem description:

When I tried use example from docs I had got this error.

bcarroll22 commented 4 years ago

Hi San, please follow all of the steps provided here to setup the provided jest preset: https://www.native-testing-library.com/docs/install#jest-preset

This will fix your issue. Good luck!

san-smith commented 4 years ago

Thanks, I will try it tomorrow.

san-smith commented 4 years ago

Yes, it helped me. Thanks!

ivan-navarro-75 commented 4 years ago
const expoPreset = require('jest-expo/jest-preset')
const jestPreset = require('@testing-library/react-native/jest-preset')

module.exports = Object.assign({}, expoPreset, jestPreset, {
  setupFiles: [...expoPreset.setupFiles, ...jestPreset.setupFiles],
  preset: '@testing-library/react-native',
})

this is my configuration to use the testing library with expo, but I have this error, not sure if it is related with the testing library

node_modules/expo/build/Expo.fx.js:1 ({"Object.":function(module,exports,require,dirname,filename,global,jest){import './environment/validate.fx'; ^^^^^^

SyntaxError: Cannot use import statement outside a module
augus-zz commented 4 years ago

Relevant code or config:

// tests/__tests__/setup.spec.tsx
import React from 'react'
import gql from 'graphql-tag'
import { useQuery } from '@apollo/react-hooks'
import { MockedProvider } from '@apollo/react-testing'
import wait from 'waait'
import { render } from '@testing-library/react-native'

// Make sure the query is also exported -- not just the component
const GET_DOG_QUERY = gql`
  query getDog($name: String) {
    dog(name: $name) {
      id
      name
      breed
    }
  }
`

const Dog: React.SFC<{ name: string }> = ({ name }) => {
  const {
    loading, error, data,
  } = useQuery(GET_DOG_QUERY, { variables: { name } })
  if (loading) return <p>Loading...</p>
  if (error) return <p>Error!</p>

  return <p>{`${data.dog.name} is a ${data.dog.breed}`}</p>
}

describe('verify apollo', () => {
  it('render', async () => {
    const mocks = [
      {
        request: {
          query: GET_DOG_QUERY,
          variables: {
            name: 'Buck',
          },
        },
        result: {
          data: {
            dog: {
              id: '1',
              name: 'Buck',
              breed: 'bulldog',
            },
          },
        },
      },
    ]

    const {
      queryByText, debug,
    } = render(
      <MockedProvider
        mocks={mocks}
        addTypename={false}
      >
        <Dog name='Buck' />
      </MockedProvider>,
    )
    debug()
    const loading = queryByText(/Loading/i)
    expect(loading).not.toBeNull()

    await wait(0) // wait for response

    debug()
    expect(queryByText('Buck is a bulldog')).toBeTruthy()
  })
})
// jest.config.js
const jestPreset = require('@testing-library/react-native/jest-preset')

module.exports = {
  preset: '@testing-library/react-native',
  // The root of your source code, typically /src
  // `<rootDir>` is a token Jest substitutes
  roots: ['<rootDir>'],

  testEnvironment: 'node',

  // Module file extensions for importing
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],

  transform: {
    '^.+\\.(ts|tsx)$': 'babel-jest',
  },
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  testPathIgnorePatterns: ['\\.snap$', '<rootDir>/node_modules/', '<rootDir>/lib/'],
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|tcomb-form-native|react-native-maps|react-native-iphone-x-helper|react-native-spinkit|react-native-user-avatar|react-native-modal|react-native-animatable|react-native-linear-gradient|react-native-firebase|react-native-qrcode-svg)/)',
  ],
  cacheDirectory: '.jest/cache',
  setupFiles: [...jestPreset.setupFiles, '<rootDir>/tests/setup.js'],
  setupFilesAfterEnv: ['@testing-library/react-native/cleanup-after-each'],
  globals: {
    'ts-jest': {
      diagnostics: {
        warnOnly: true,
      },
    },
  },
}

What you did:

setup a test to verify demo from https://www.apollographql.com/docs/react/development-testing/testing/

What happened:

failed to query text Loading... in render result

Problem description:

yarn test tests/__tests__/setup.spec.tsx
yarn run v1.22.0
$ node --max-old-space-size=4096 ./node_modules/.bin/jest --maxWorkers 2 --forceExit --ci --detectOpenHandles tests/__tests__/setup.spec.tsx
 FAIL  tests/__tests__/setup.spec.tsx
  verify apollo
    ✕ render (41ms)

  ● verify apollo › render

    expect(received).not.toBeNull()

    Received: null

      61 |     debug()
      62 |     const loading = queryByText(/Loading/i)
    > 63 |     expect(loading).not.toBeNull()
         |                         ^
      64 |
      65 |     await wait(0) // wait for response
      66 |

      at toBeNull (tests/__tests__/setup.spec.tsx:63:25)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:45:40)
      at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:271:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:97:21)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:45:40)
      at invoke (node_modules/regenerator-runtime/runtime.js:135:20)
      at node_modules/regenerator-runtime/runtime.js:170:11
      at tryCallTwo (node_modules/promise/lib/core.js:45:5)
      at doResolve (node_modules/promise/lib/core.js:200:13)
      at new Promise (node_modules/promise/lib/core.js:66:3)

  console.log node_modules/@testing-library/react-native/dist/index.js:106
    <View
      pointerEvents="box-none"
      style={
        Object {
          "flex": 1,
        }
      }
    >
      <View
        collapsable={true}
        pointerEvents="box-none"
        style={
          Object {
            "flex": 1,
          }
        }
      >
        <p>
          Loading...
        </p>
      </View>
    </View>

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.997s
Ran all test suites matching /tests\/__tests__\/setup.spec.tsx/i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

from debug output. we could see Loading...