Rip*_*s55 3 unit-testing firebase reactjs jestjs google-cloud-firestore
可以使用 firebase firestore 进行测试吗?我一直在遵循测试教程,并且测试对其他人有用但对我不起作用。
\n我的组件代码在客户端中工作,所以我很困惑为什么会收到此错误。
\n我只找到了有关在 firebase 中测试安全规则的信息,但没有找到有关 firestore 的信息,这是否意味着它是我们唯一可以测试的东西?
\n这是我得到的错误:
\n FIRESTORE (9.6.1) INTERNAL ASSERTION FAILED: Unexpected state\n\n at fail (node_modules/@firebase/firestore/src/util/assert.ts:40:9)\n at hardAssert (node_modules/@firebase/firestore/src/util/assert.ts:54:5)\n at fromBytes (node_modules/@firebase/firestore/src/remote/serializer.ts:252:5)\n at fromWatchChange (node_modules/@firebase/firestore/src/remote/serializer.ts:475:25)\n at PersistentListenStream.onMessage (node_modules/@firebase/firestore/src/remote/persistent_stream.ts:642:25)\n at node_modules/@firebase/firestore/src/remote/persistent_stream.ts:517:21\n at node_modules/@firebase/firestore/src/remote/persistent_stream.ts:570:18\n at node_modules/@firebase/firestore/src/util/async_queue_impl.ts:135:7\n at node_modules/@firebase/firestore/src/util/async_queue_impl.ts:186:14\n\n\xe2\x97\x8f if the user is fetched, the name is shown\n\n Unable to find an element with the text: /James/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.\nRun Code Online (Sandbox Code Playgroud)\n我的组件代码:
\nfunction Hellopage() {\n const [userData, setUserData] = useState();\n\n const getData = async () => {\n const docRef = doc(firestore, "users", "pW5CizOJOpXezr5lGGshDmKdVzZ2");\n const docSnap = await getDoc(docRef);\n if (docSnap.exists()) {\n setUserData(docSnap.data());\n } else {\n // doc.data() will be undefined in this case\n console.log("No such document!");\n }\n };\n\n useEffect(() => {\n getData();\n }, []);\n\n return (\n <div>\n <div>{userData?.name}</div>\n </div>\n );\n}\n\nexport default Hellopage;\nRun Code Online (Sandbox Code Playgroud)\n我的测试:
\ntest("if the user is fetched, the name is shown", async () => {\n const result = render(<HelloPage />);\n\n expect(await result.findByText(/James/i)).toBeInTheDocument();\n});\n\nRun Code Online (Sandbox Code Playgroud)\n
这是测试环境的问题jsdom。node使用firestore时应将环境切换回默认值。如果您依赖jsdom其他测试,最简单的方法可能是在文件顶部使用文档块:
/**
* @jest-environment node
*/
Run Code Online (Sandbox Code Playgroud)
您可能会遇到此特定测试的问题,因为 React 和 Firebase 紧密耦合,React 需求jsdom和 Firebase 需求node。这可以通过使用基于 DOM 的实际测试环境(如 cypress)来解决,或者通过提取函数并使用模拟来与 React 分开测试 firebase。第二种方法更好,因为它意味着在测试 ui 时不访问数据库:
/**
* @jest-environment node
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2678 次 |
| 最近记录: |