[fix] call Image 'onLoad' when image is loaded from cache

Fix #452
Close #712
This commit is contained in:
Zero Cho
2017-11-10 10:55:30 -08:00
committed by Nicolas Gallagher
parent c22a9aff7d
commit 92952ee746
2 changed files with 35 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
/* eslint-env jasmine, jest */
import Image from '../';
import ImageLoader from '../../../modules/ImageLoader';
import ImageUriCache from '../ImageUriCache';
import React from 'react';
import { mount, shallow } from 'enzyme';
@@ -155,6 +156,34 @@ describe('components/Image', () => {
expect(component.prop('testID')).toBe('testID');
});
describe('prop "onLoad"', () => {
test('fires after image is loaded', () => {
jest.useFakeTimers();
ImageLoader.load = jest.fn().mockImplementation((_, onLoad, onError) => {
onLoad();
});
const onLoadStub = jest.fn();
shallow(<Image onLoad={onLoadStub} source="https://test.com/img.jpg" />);
jest.runOnlyPendingTimers();
expect(ImageLoader.load).toBeCalled();
expect(onLoadStub).toBeCalled();
});
test('fires even if the image is cached', () => {
jest.useFakeTimers();
ImageLoader.load = jest.fn().mockImplementation((_, onLoad, onError) => {
onLoad();
});
const onLoadStub = jest.fn();
const uri = 'https://test.com/img.jpg';
shallow(<Image onLoad={onLoadStub} source={uri} />);
ImageUriCache.add(uri);
jest.runOnlyPendingTimers();
expect(ImageLoader.load).not.toBeCalled();
expect(onLoadStub).toBeCalled();
});
});
test('passes other props through to underlying View', () => {
const fn = () => {};
const component = shallow(<Image onResponderGrant={fn} />);

View File

@@ -140,12 +140,18 @@ class Image extends Component {
this._isMounted = true;
if (this._imageState === STATUS_PENDING) {
this._createImageLoader();
} else if (this._imageState === STATUS_LOADED) {
const { onLoad } = this.props;
onLoad && onLoad();
}
}
componentDidUpdate() {
if (this._imageState === STATUS_PENDING) {
this._createImageLoader();
} else if (this._imageState === STATUS_LOADED) {
const { onLoad } = this.props;
onLoad && onLoad();
}
}