running mount() in react native Not Possible?

江枫思渺然 提交于 2019-12-22 13:06:31

问题


This post follows up with my previous question:

previous question

I have come across a test which requires me to run mount in react native. I have gone through the documentation in jest and have found that before running the test suite you specifically need to setup a test environment capable of running jsdom for mount to work:

The link to docs is: testEnvironment

Because of it's horrible documentation. I can't figure out how to create the customEnvironment class and what after that? what do I do with the global object? How to use it in my test file which currently looks like:

describe('Estimate', () => {
  test('Estimate component Exists', () => {
    const onPressFunction = jest.fn()
    const obj = shallow(
      <Estimate onPress={onPressFunction} />
    )
    expect(obj.find('TextInput').exists()).toBe(true)
  })

  test('Estimate returns value on button press', () => {
    const onPressFunction = jest.fn()
    const obj = shallow(
      <Estimate onPress={onPressFunction} />
    )
    obj.find('TextInput').first().simulate('keypress', { key: '1' })
    obj.find('Button').first().props().onPress()
    expect(onPressFunction.toHaveBeenCalledWith('1'))
  })
})

回答1:


I just made it work had to import three packages from npm:

  1. jsdom
  2. react-native-mock-renderer
  3. jest-environment-jsdom

Also my setup.mjs file looks like:

// @note can't import shallow or ShallowWrapper specifically
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
// eslint-disable-next-line
import { format } from 'prettier'

Enzyme.configure({ adapter: new Adapter() })

// Make Enzyme functions available in all test files without importing
global.shallow = Enzyme.shallow

Enzyme.ShallowWrapper.prototype.jsx = function jsx () {
  const placeholder = '{ something: null }'
  const obj = this.debug({ ignoreProps: false, verbose: true }).replace(/{\.\.\.}/g, placeholder)

  return format(obj, {
    parser: 'babylon',
    filepath: 'test/setup.mjs',
    trailingComma: 'all',
    semi: false,
    arrowParens: 'always',
  })
    .replace(new RegExp(placeholder, 'g'), '{...}')
    .replace(';<', '<')
}
// the html function just throws errors so it's just reset to be the jsx function
Enzyme.ShallowWrapper.prototype.html = Enzyme.ShallowWrapper.prototype.jsx

jest.mock('react-native-device-info', () => {
  return {
    getDeviceLocale: () => 'en',
    getDeviceCountry: () => 'US',
  }
})

jest.mock('react-native-custom-tabs', () => ({
  CustomTabs: {
    openURL: jest.fn(),
  },
}))

jest.mock('react-native-safari-view', () => ({
  isAvailable: jest.fn(),
  show: jest.fn(),
}))



const { JSDOM } = require('jsdom')


const jsdom = new JSDOM()
const { window } = jsdom
function copyProps (src, target) {
  const props = Object.getOwnPropertyNames(src)
    .filter((prop) => typeof target[prop] === 'undefined')
    .map((prop) => Object.getOwnPropertyDescriptor(src, prop))
  Object.defineProperties(target, props)
}

global.window = window
global.document = window.document
global.navigator = {
  userAgent: 'node.js',
}
copyProps(window, global)
Enzyme.configure({ adapter: new Adapter() })

// Ignore React Web errors when using React Native
// allow other errors to propagate if they're relevant
const suppressedErrors = /(React does not recognize the.*prop on a DOM element|Unknown event handler property|is using uppercase HTML|Received `true` for a non-boolean attribute `accessible`|The tag.*is unrecognized in this browser)/
const realConsoleError = console.error
console.error = (message) => {
  if (message.match(suppressedErrors)) {
    return
  }
  realConsoleError(message)
}
require('react-native-mock-render/mock')

Test looks like:

 test('Estimate returns value on button press', () => {
    const onPressFunction = jest.fn()
    const tree = mount(
      <Estimate onPress={onPressFunction} />
    )
    console.log(tree.children().first().html())
  })

Works like a charm!



来源:https://stackoverflow.com/questions/52301227/running-mount-in-react-native-not-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!