我正在尝试为我构建的反应组件编写测试,这些组件navigator.geolocation.getCurrentPosition()在类似的方法中使用(我的组件的粗略示例):
class App extends Component {
constructor() {
...
}
method() {
navigator.geolocation.getCurrentPosition((position) => {
...code...
}
}
render() {
return(...)
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用create-react-app,其中包括一个测试:
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
Run Code Online (Sandbox Code Playgroud)
此测试失败,在控制台中打印出来:
TypeError: Cannot read property 'getCurrentPosition' of undefined
Run Code Online (Sandbox Code Playgroud)
我是React的新手,但对于角度1.x有相当多的经验.在angular中,通常模拟(在beforeEach中的测试中)函数,"服务"和全局对象方法,如navigator.geolocation.etc.我花了很多时间研究这个问题,这段代码是我最接近模拟的代码:
global.navigator = {
geolocation: {
getCurrentPosition: jest.fn()
}
}
Run Code Online (Sandbox Code Playgroud)
我把它放在App的测试文件中,但没有效果.
我如何"模拟"这个导航器方法并让测试通过?
编辑:我研究了一个名为geolocation的库,它应该包含navigator.getCurrentPosition在节点环境中使用.如果我理解正确,jest在节点环境中运行测试并使用JSDOM来模拟像window.我无法找到有关JSDOM支持的更多信息navigator.上面提到的库在我的反应应用程序中不起作用.使用特定方法getCurrentPosition只会返回undefined,即使库本身已正确导入并在App类的上下文中可用.
我们应该如何在带有React钩子的Flow类型注释中使用useState?我尝试搜索一些应如何实施的示例,但找不到任何内容。
我尝试了这个:
const [allResultsVisible, setAllResultsVisible]: [ boolean, (boolean) => void, ] = useState(false);
Run Code Online (Sandbox Code Playgroud)
不会引发任何与流相关的错误,但是我不确定这是否正确,还是注释该钩子的最佳方法。如果我的尝试不正确或最佳方法,我应该怎么做?
我正在尝试使用来在数组中查找对象Array.prototype.includes。这可能吗?我意识到浅层比较和深层比较之间是有区别的。这是下面的代码返回false的原因吗?我找不到的相关答案Array.includes()。
我有一个看起来像这样的组件(非常简化的版本):
const component = (props: PropTypes) => {
const [allResultsVisible, setAllResultsVisible] = useState(false);
const renderResults = () => {
return (
<section>
<p onClick={ setAllResultsVisible(!allResultsVisible) }>
More results v
</p>
{
allResultsVisible &&
<section className="entity-block--hidden-results">
...
</section>
}
</section>
);
};
return <div>{ renderResults() }</div>;
}
Run Code Online (Sandbox Code Playgroud)
加载使用此组件的页面时,出现以下错误:Uncaught Invariant Violation: Rendered more hooks than during the previous render.我试图找到此错误的解释,但搜索未返回任何结果。
当我稍微修改组件时:
const component = (props: PropTypes) => {
const [allResultsVisible, setAllResultsVisible] = useState(false);
const handleToggle = () => {
setAllResultsVisible(!allResultsVisible);
} …Run Code Online (Sandbox Code Playgroud) reactjs ×3
javascript ×2
arrays ×1
flowtype ×1
jestjs ×1
object ×1
react-hooks ×1
unit-testing ×1