reactjs - 测试使用 try/catch 并调用 Image.getSize 的 React Native 组件的函数

标签 reactjs react-native jestjs enzyme

我正在尝试为组件内定义的以下 React Native 函数编写一个 Jest 测试:

该函数获取一个具有两个字段的数据对象:urlimage ,并根据它们的值设置组件的状态。

当 data.image 不为空,而是图像的 URI 时,如何测试该函数的任何建议? (例如 http://a.com/a.png )

getArticleDetails (data) {
  const { url, image } = data

  if (!image) {
    this.setState({ url, image })
  } else {
    try {
      Image.getSize(image, (width, height) => {
        if (width > 2000 || height > 2000) {
          image = null
        }
        this.setState({ url, image })
      }, (error) => {
        image = null
        this.setState({ url, image, title, description })
      })
    } catch (e) {
      image = null
      this.setState({ url, image })
    }
  }
}

最佳答案

最好的方法是模拟 Image.getSize()并从调用时传递的参数中获取回调。

这是一个简单的工作示例:

例子.js

import * as React from 'react';
import { Image } from 'react-native';

export class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { };
  }

  getArticleDetails (data) {
    let { url, image } = data

    if (!image) {
      this.setState({ url, image })
    } else {
      try {
        Image.getSize(image, (width, height) => {
          if (width > 2000 || height > 2000) {
            image = null
          }
          this.setState({ url, image })
        }, (error) => {
          image = null
          this.setState({ url, image, title, description });
        })
      } catch (e) {
        image = null
        this.setState({ url, image })
      }
    }
  }

  render() {
    return null;
  }
}

例子.test.js

import * as React from 'react';
import { Image } from 'react-native';
import renderer from 'react-test-renderer';

import { Example } from './example';

describe('Example', () => {
  it('should call Image.getSize()', () => {
    // create a mock implementation for Image.getSize()
    const getSizeMock = jest.spyOn(Image, 'getSize');
    getSizeMock.mockImplementation(() => { /* do nothing */ });

    const data = {
      url: 'mocked url',
      image: 'just has to make !image return false'
    }

    const comp = renderer.create(<Example/>).root.instance;
    comp.getArticleDetails(data);

    expect(getSizeMock).toHaveBeenCalledTimes(1);
    // get the arguments that Image.getSize() was called with
    // (see https://jestjs.io/docs/en/mock-function-api#mockfnmockcalls)
    const getSizeArgs = getSizeMock.mock.calls[0];

    expect(getSizeArgs[0]).toBe(data.image); // first arg should be data.image
    const success = getSizeArgs[1]; // second arg is the success callback
    const error = getSizeArgs[2]; // third arg is the error callback

    // test the success callback with width <= 2000 and height <= 2000
    success(100, 100);
    expect(comp.state.url).toBe(data.url);
    expect(comp.state.image).toBe(data.image);

    // test the success callback with width > 2000 and height > 2000
    success(2001, 2001);
    expect(comp.state.url).toBe(data.url);
    expect(comp.state.image).toBe(null);

    // restore Image.getSize()
    getSizeMock.mockRestore();
  });
});

关于reactjs - 测试使用 try/catch 并调用 Image.getSize 的 React Native 组件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51859039/

相关文章:

javascript - 如何获得在 React 和 Jest 中循环内运行的组件的单元测试覆盖率

android - 在 react-native-map 中切换 maptype

reactjs - 使用 Hooks 在功能组件中 react 导航标题

react-native - 在 TimePickerAndroid react native 中设置最短时间

typescript - 如何解决 Testcafe 和 Jest 之间的类型冲突? ("Cannot redeclare block-scoped variable ' 测试'")

jestjs - 运行特定的 jest 项目

javascript - React ref 组件不暴露方法

javascript - 流路由器重定向数据插入 Meteor js

ReactJS:如何防止浏览器缓存静态文件?

javascript - react : How could I add a fade out animation on delete on dynamically generated table entries?