【问题标题】:running mount() in react native Not Possible?在本机反应中运行 mount() 不可能?
【发布时间】:2019-02-17 10:51:06
【问题描述】:

这篇文章跟进了我之前的问题:

previous question

我遇到了一个测试,需要我在 react native 中运行 mount。我开玩笑地浏览了文档,发现在运行测试套件之前,您特别需要设置一个能够运行 jsdom 的测试环境才能挂载工作:

文档的链接是: testEnvironment

因为它的文档很糟糕。我不知道如何创建 customEnvironment 类,然后呢?我该如何处理全局对象?如何在我目前看起来像这样的测试文件中使用它:

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'))
  })
})

【问题讨论】:

标签: javascript reactjs react-native jestjs enzyme


【解决方案1】:

我刚刚让它工作了,必须从 npm 导入三个包:

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

另外我的 setup.mjs 文件看起来像:

// @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('Estimate returns value on button press', () => {
    const onPressFunction = jest.fn()
    const tree = mount(
      <Estimate onPress={onPressFunction} />
    )
    console.log(tree.children().first().html())
  })

像魅力一样工作!

【讨论】:

  • 谢谢你!超级有用
  • 你能解释一下你的安装文件吗?像 react-native-safari-view 这样需要哪些模拟?
猜你喜欢
  • 1970-01-01
  • 2017-09-20
  • 2021-06-24
  • 2021-08-03
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多