玩笑测试验证数据道具

时间:2018-08-16 03:33:22

标签: javascript react-native testing jestjs enzyme

我是个玩笑新手,想学习有关如何编写测试的基础知识。如何编写一个简单的测试来验证uri包含/返回值?

renderProfileImage () {
    const apiUrl = 'site.com'
    const profileImagePath = this.props.data.field_profile_image

    if (profileImagePath !== '') {
      return <Image
        style={styles.profile}
        source={this.state.imageLoading ? require('../img/profileImagePlaceholder.png') : { uri: `${apiUrl}${profileImagePath}` }}
        onLoadEnd={(e) => this.setState({ imageLoading: false })}
      />
    }

this.props.data.field_profile_image返回/photo.png

1 个答案:

答案 0 :(得分:1)

请记住"React elements are plain objects"

import * as React from 'react';
import renderer from 'react-test-renderer';

import { MyComponent } from './path-to-your-component';

describe('renderProfileImage', () => {
  it('should set the correct uri', () => {
    const comp = renderer.create(<MyComponent data={{
      field_profile_image: '/path-to-the-image'
    }}/>).root.instance;
    // element is just an object representing an <Image>...
    const element = comp.renderProfileImage();
    // ...so check that element.props.source was set correctly
    expect(element.props.source).toEqual({ uri: 'site.com/path-to-the-image' });
  });
});