Noh | エンジニア向け情報共有コミュニティ
Signup / Login

The process times out when testing Firestore security rules.

firebase
firestore
javascript

投稿日: 2024/06/25

更新日: 2024/07/02

This article is a translation of the following article.

https://noh.ink/articles/eJwDlJ3C86J3uXa2tvUo

This is a memo of the troubles encountered when introducing tests for Firestore security rules.

Problem encountered

I tried writing a test like the following:

test( "Can't create", async () => { await assertFails( addDoc(collection(db, "users"), { displayName: "NewTestUser", }) ) } )

I tried to start the emulator and run the test, but it failed as shown below.

The addDoc process is not completing and timing out as it is.

> jest firebase/tests/rules/users.test.ts FAIL firebase/tests/rules/users.test.ts (11.328 s) users When not logged in ✕ Can't create (5013 ms) ● users › When not logged in › Can't create thrown: "Exceeded timeout of 5000 ms for a test. Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout." 24 | }) 25 | > 26 | test("Can't create", async () => { | ^ 27 | await assertFails( 28 | addDoc(collection(db, "users"), { 29 | displayName: "NewTestUser",

Solution

The investigation into the cause was difficult, but the answers on the following site were helpful as reference.

The failure was due to testEnvironment: jsdom in jest.config.js.
Changing it to the default testEnvironment: node will prevent timeouts.

Correction Example

When testing in a shared environment with React and Next.js, it is recommended to use different configurations by separating the execution commands.

Composition

├── firebase │   ├── data │   ├── tests │   │ ├── helpers │   │ └── rules │ ├── .firebaserc │ ├── firebase.json │ └── firestore.rules ├── public └── src ├── pages │   └── api ├── styles └── test └── pages

Let's assume a feeling like that.

Test Config for NextJS

jest.config.js

module.exports = { roots: ["<rootDir>"], testMatch: ["**/*.+(spec|test).+(ts|tsx|js)"], testPathIgnorePatterns: ["<rootDir>/firebase/"], transform: { "^.+\\.(ts|tsx)$": "ts-jest", }, moduleDirectories: ["node_modules"], testEnvironment: "jsdom", }

Test Config for Firestore Security Rules

jest.config.firebase.js

module.exports = { roots: ["<rootDir>"], testMatch: ["<rootDir>/firebase/**/*.+(spec|test).+(ts|tsx|js)"], transform: { "^.+\\.(ts|tsx)$": "ts-jest", }, moduleDirectories: ["node_modules"], testEnvironment: "node", }

Execution Commands for Each

package.json

"scripts": { "test": "jest", "test_firebase": "jest --config jest.config.firebase.js" },

Table of Contents