我是编码和制作 React 应用程序的新手。这是获取地理位置的代码的一部分
const getLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
});
}
};
const errorCallback = (error) => {
switch (error.code) {
case error.PERMISSION_DENIED:
setErrorMessage(error.message);
break;
default:
setErrorMessage("");
break;
}
};
return (
<div>
{errorMessage && <p>{errorMessage}</p>}
</div>
);
}
然后我用
测试这部分import { render, screen, waitFor, act } from '@testing-library/react';
import App from './App'; // Adjust the import according to your file structure
// Mock the geolocation API
global.navigator.geolocation = {
getCurrentPosition: jest.fn()
};
test('handles geolocation error', async () => {
// Mock the getCurrentPosition function to return an error asynchronously
navigator.geolocation.getCurrentPosition.mockImplementationOnce((success, error) => {
error({
code: 1,
message: "User denied geolocation prompt"
});
});
render(<App />);
// Wait for the error message to appear
await waitFor(() => {
expect(screen.getByText("User denied geolocation prompt")).toBeInTheDocument();
}, { timeout: 1000 });
});
因此测试用例将错误设置为代码1,即权限被拒绝错误。但是,切换功能将转到默认情况,而不是权限被拒绝的情况。
错误的正确传递是这样的
navigator.geolocation.getCurrentPosition.mockImplementationOnce((success,error) => Promise.resolve( error({ code: 1, message: "User denied geolocation prompt", PERMISSION_DENIED: 1 })