gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:15:27 31 4
gpt4 key购买 nike

我正在尝试为组件内定义的以下 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com