【发布时间】:2021-08-31 19:46:28
【问题描述】:
我正在为我的应用程序编写一些测试,并且我正在尝试模拟 Linking 模块。我正在使用jest。
Linking.canOpenURL 模拟它工作正常(toHaveBeenCalled 正在返回 true),但永远不会调用 openURL 模拟。
function mockSuccessLinking() {
const canOpenURL = jest
.spyOn(Linking, 'canOpenURL')
.mockImplementation(() => Promise.resolve(true));
const openURL = jest
.spyOn(Linking, 'openURL')
.mockImplementation(() => Promise.resolve(true));
return { canOpenURL, openURL };
}
问题是openURL没有被调用。
这是测试:
test('should open url when there is a proper app the open it', async () => {
const { canOpenURL, openURL } = mockSuccessLinking();
const { result } = renderHook(() =>
useApplyToJob('https://www.google.com/'),
);
const [apply] = result.current;
// Act
apply();
// Assert
expect(result.current[1].error).toBeNull();
expect(canOpenURL).toHaveBeenCalled();
expect(openURL).toHaveBeenCalled();
});
这是正在测试的钩子:
export function useApplyToJob(url) {
const [error, setError] = useState(null);
const apply = () => {
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url);
} else {
setError(`Don't know how to open ${url}`);
}
});
};
return [apply, { error }];
}
【问题讨论】:
标签: react-native jestjs react-hooks react-hooks-testing-library