firebase-js-sdk icon indicating copy to clipboard operation
firebase-js-sdk copied to clipboard

Upgrade to 9.2.0 gives error in jest unit tests

Open LanderBeeuwsaert opened this issue 5 years ago • 28 comments

[REQUIRED] Describe your environment

  • Operating System version: Windows 10
  • Browser version: ---
  • Firebase SDK version: 9.1.3 upgrade to 9.2.0
  • Firebase Product: ----

[REQUIRED] Describe the problem

When upgrading to firebase 9.2.0 from 9.1.3 our jest unit tests start to fail with the following message:

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

We do use AngularFire (7.1.1) as well. Running our Angular application itself seems to be ok. So it seems to be related with the upgrade + our jest configuration maybe?

Adding the full test log below:

PASS spec/tests/app/import-service/validators/country.validator.spec.ts PASS spec/tests/app/patchers/organisation/1_0.patcher.spec.ts PASS spec/tests/app/import-service/validators/firestore-doc.validator.spec.ts PASS spec/tests/app/functions/country-service-backend.spec.ts PASS spec/tests/app/scoring/calculate-partial-score.spec.ts PASS spec/tests/app/import-service/validators/unique-column-value.validator.spec.ts PASS spec/tests/app/version-patcher-service.spec.ts PASS spec/tests/app/import-service/validators/column-exclusive-required.validator.spec.ts PASS spec/tests/app/import-service/validators/array-match.validator.spec.ts PASS spec/tests/app/import-service/validators/vat.validator.spec.ts PASS spec/tests/app/import-service/validators/positive-integer.validator.spec.ts PASS spec/tests/app/import-service/validators/inbetween-integer.validator.spec.ts PASS spec/tests/app/import-service/validators/length.validator.spec.ts PASS spec/tests/app/import-service/validators/firestore-key.validator.spec.ts PASS spec/tests/app/import-service/validators/trimmed.validator.spec.ts PASS spec/tests/app/import-service/validators/email.validator.spec.ts PASS spec/tests/app/import-service/validators/split-and-apply-multiple-validators.spec.ts PASS spec/tests/app/import-service/import.service.spec.ts FAIL spec/tests/app/generic-competition-admin/exercises-import.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

FAIL spec/tests/app/helpers.service.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

FAIL spec/tests/app/trampoline/judges-trampoline-service.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

PASS spec/tests/app/functions/util-helpers.spec.ts ● Console

console.warn
  {"severity":"WARNING","message":"Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail"

}

  at write (functions/node_modules/firebase-functions/lib/logger/index.js:44:78)
  at warn (functions/node_modules/firebase-functions/lib/logger/index.js:95:5)
  at setup (functions/node_modules/firebase-functions/lib/setup.js:56:31)
  at Object.<anonymous> (functions/node_modules/firebase-functions/lib/index.js:67:19)

PASS spec/tests/app/scoring/acro-specific-ranking.service.spec.ts ● Console

console.warn
  {"severity":"WARNING","message":"Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail"

}

  at write (functions/node_modules/firebase-functions/lib/logger/index.js:44:78)
  at warn (functions/node_modules/firebase-functions/lib/logger/index.js:95:5)
  at setup (functions/node_modules/firebase-functions/lib/setup.js:56:31)
  at Object.<anonymous> (functions/node_modules/firebase-functions/lib/index.js:67:19)

PASS spec/tests/app/generic-competitions/generic-acro-ranking.service.spec.ts ● Console

console.warn
  {"severity":"WARNING","message":"Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail"

}

  at write (functions/node_modules/firebase-functions/lib/logger/index.js:44:78)
  at warn (functions/node_modules/firebase-functions/lib/logger/index.js:95:5)
  at setup (functions/node_modules/firebase-functions/lib/setup.js:56:31)
  at Object.<anonymous> (functions/node_modules/firebase-functions/lib/index.js:67:19)

FAIL spec/tests/app/scoring/team-ranking.service.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

Summary of all failing tests FAIL spec/tests/app/generic-competition-admin/exercises-import.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

FAIL spec/tests/app/helpers.service.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

FAIL spec/tests/app/trampoline/judges-trampoline-service.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

FAIL spec/tests/app/scoring/team-ranking.service.spec.ts ● Test suite failed to run

TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js'

  at Function.createRequire (node_modules/jest-runtime/build/index.js:1418:23)
  at Object.<anonymous> (node_modules/@firebase/firestore/src/platform/node/grpc_connection.ts:43:24)
  at Object.<anonymous> (node_modules/@firebase/firestore-compat/dist/index.node.cjs.js:6:17)

LanderBeeuwsaert avatar Oct 30 '21 11:10 LanderBeeuwsaert

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

google-oss-bot avatar Oct 30 '21 11:10 google-oss-bot

I got a similar error when using firebase in Sveltekit deployed on Vercel.

2021-11-01T03:48:43.208Z 935c63ac-2b9c-4c39-b5d8-30afa3e6674e ERROR TypeError [ERR_INVALID_ARG_VALUE]: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received undefined at Function.createRequire (internal/modules/cjs/loader.js:1173:11) at Object.<anonymous> (/var/task/index.js:550702:38) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29) at ModuleJob.run (internal/modules/esm/module_job.js:170:25) at async Loader.import (internal/modules/esm/loader.js:178:24) at async getListener (/var/task/___vc/__launcher.js:33:11) { code: 'ERR_INVALID_ARG_VALUE'}RequestId: 935c63ac-2b9c-4c39-b5d8-30afa3e6674e Error: Runtime exited with error: exit status 1Runtime.ExitError

tonprince avatar Nov 01 '21 03:11 tonprince

Note that you are loading the Nodejs bundle index.node.cjs.js in testing? Is it what you intend to do, or should you use the browser bundle instead?

The root cause of the issue is this line, which we added to allow us to use require in the esm mode in Nodejs.

Feiyang1 avatar Nov 01 '21 21:11 Feiyang1

Hi @Feiyang1 , well we actually have our tests for the front-end application (angular + angularFire + firebase) in the same location as our tests for the functions (firebase-admin).

Probably that's indeed not a normal setup and this issue wouldn't occur if we would separate our tests? Or is there another workaround or fix?

LanderBeeuwsaert avatar Nov 01 '21 22:11 LanderBeeuwsaert

Your setup sounds fine to me as long as you are able to specify different configurations for your FE and BE tests respectively. Or are you saying you run both FE and BE tests as a single test run?

Are you able to instruct the FE tests to usenode_modules/@firebase/firestore-compat/dist/index.esm2017.js the browser bundle to load firestore?

Is webpack (since you mentioned Angular) involved at all to bundle tests before running them in jest? if so, you can use the mainFields option for webpack to use the browser bundle.

If you could provide a min repro, I can take a closer look and it will be much easier for me to find where the problem is.

Feiyang1 avatar Nov 01 '21 22:11 Feiyang1

Try this 👍

https://github.com/tja4472/angularfire-jest-tests

HTH

tja4472 avatar Nov 02 '21 11:11 tja4472

Okay, thanks for the repro. It seems that external dependencies are not bundled for testing, and they are resolved using require() at runtime by Jest. That means the main field is used to resolve packages, and the main field points to the Nodejs specific builds for Firebase packages. But since you are testing your FE code, and Jest is running in simulated browser mode, you really want to load the browser bundles from Firebase.

To do that, you need to define a custom resolver to tell Jest to resolve firebase packages using their browser bundles:

  1. Create a file my-module-resolve.js at the root of the project (you can use any name, but remember to use the same one when setting the path to it in jest.config.js in step 2)
// my-module-resolve.js
module.exports = (request, options) => {
  // Call the defaultResolver, so we leverage its cache, error handling, etc.
  return options.defaultResolver(request, {
    ...options,
    // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
    packageFilter: pkg => {
      if(pkg.name.startsWith('@firebase')) {
        return {
          ...pkg,
          // Alter the value of `main` before resolving the package
          main: pkg.esm5 || pkg.module,
        };
      }

      return pkg;
    },
  });
};
  1. Add 2 fields to jest.config.js:
module.exports = {
  ....
  // set the value to the custom resolver created in step 1
  resolver: '<rootDir>/my-module-resolve.js',
  // browser bundles in firebase are ESM, transform them to CJS to work in Jest
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(?!(@firebase.*)/)"
  ]
};

This should solve the The argument 'filename' must be a file URL object error from the original post.

You can also solve the problem by bundling tests with all external dependencies before running them in Jest, but that will probably slow down the tests significantly and beats the purpose of using Jest with Angular.

I also want to point out that this could be an issue for any packages, not just Fireabase, that support both Nodejs and Browser, especially if they supply different bundles/implementations for them, so I think Jest's default strategy to use the main field to resolve packages for browser tests is a bit flawed.

@tja4472 There is another error I got from the repro, which the above workaround doesn't help - Cannot find module 'rxfire/auth' from 'node_modules/@angular/fire/bundles/angular-fire-auth.umd.js', but I think it's unrelated to the original issue, and is from @angular/fire. If you think it is still an issue, please open an issue with them.

Feiyang1 avatar Nov 02 '21 19:11 Feiyang1

I've got the same issue, but since in tests we do not rely on the details of the implementation of the 3rd-party library (which in general considered bad test practice), we just mocked entire firebase/firestore in tests setup:

jest.mock("firebase/firestore", () => {
    return {
        getFirestore: jest.fn(),
    };
});

urakozz avatar Nov 03 '21 20:11 urakozz

Same issue as-well however I'm working with React and the solution above doesn't seem to work due to create-react-app's limitations. Thoughts?

ruizaj13 avatar Nov 04 '21 22:11 ruizaj13

I know it is bad. But it fixed using [email protected]

stories2 avatar Nov 10 '21 11:11 stories2

After applying your proposed solution @Feiyang1 using the custom resolver, the original error TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js' went away but now I receive the following error:

Cannot find module '@firebase/app' from 'node_modules/firebase/app/dist/index.cjs.js'

    Require stack:
      node_modules/firebase/app/dist/index.cjs.js
      ...

Does anyone else encounter this? The installed "firebase" version is 9.4.0.

sceee avatar Nov 10 '21 12:11 sceee

After applying your proposed solution @Feiyang1 using the custom resolver, the original error TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js' went away but now I receive the following error:

Cannot find module '@firebase/app' from 'node_modules/firebase/app/dist/index.cjs.js'

    Require stack:
      node_modules/firebase/app/dist/index.cjs.js
      ...

Does anyone else encounter this? The installed "firebase" version is 9.4.0.

~~Somehow, it seems after deleting node_modules several rounds and somehow modifying package-lock.json the error went away... I don't know what actually resolved the issue.~~

// Edit Sorry, this message was incorrect, I messed something up during the trials (probably mixed in urakozz's solution).

The above error (Cannot find module '@firebase/app' from 'node_modules/firebase/app/dist/index.cjs.js') still occurs when just using this solution by @Feiyang1 .

sceee avatar Nov 10 '21 17:11 sceee

This this error too. Effectively preventing us from upgrading.

maccman avatar Nov 14 '21 04:11 maccman

Okay, thanks for the repro. It seems that external dependencies are not bundled for testing, and they are resolved using require() at runtime by Jest. That means the main field is used to resolve packages, and the main field points to the Nodejs specific builds for Firebase packages. But since you are testing your FE code, and Jest is running in simulated browser mode, you really want to load the browser bundles from Firebase.

To do that, you need to define a custom resolver to tell Jest to resolve firebase packages using their browser bundles:

  1. Create a file my-module-resolve.js at the root of the project (you can use any name, but remember to use the same one when setting the path to it in jest.config.js in step 2)
// my-module-resolve.js
module.exports = (request, options) => {
  // Call the defaultResolver, so we leverage its cache, error handling, etc.
  return options.defaultResolver(request, {
    ...options,
    // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
    packageFilter: pkg => {
      if(pkg.name.startsWith('@firebase')) {
        return {
          ...pkg,
          // Alter the value of `main` before resolving the package
          main: pkg.esm5 || pkg.module,
        };
      }

      return pkg;
    },
  });
};
  1. Add 2 fields to jest.config.js:
module.exports = {
  ....
  // set the value to the custom resolver created in step 1
  resolver: '<rootDir>/my-module-resolve.js',
  // browser bundles in firebase are ESM, transform them to CJS to work in Jest
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(?!(@firebase.*)/)"
  ]
};

This should solve the The argument 'filename' must be a file URL object error from the original post.

You can also solve the problem by bundling tests with all external dependencies before running them in Jest, but that will probably slow down the tests significantly and beats the purpose of using Jest with Angular.

I also want to point out that this could be an issue for any packages, not just Fireabase, that support both Nodejs and Browser, especially if they supply different bundles/implementations for them, so I think Jest's default strategy to use the main field to resolve packages for browser tests is a bit flawed.

@tja4472 There is another error I got from the repro, which the above workaround doesn't help - Cannot find module 'rxfire/auth' from 'node_modules/@angular/fire/bundles/angular-fire-auth.umd.js', but I think it's unrelated to the original issue, and is from @angular/fire. If you think it is still an issue, please open an issue with them.

This is a blocker for my team as well. We applied the same recommended module resolution fix, but received the "Cannot find module 'rxfire/auth' from..." error.

Our project is using React.

andrewrisse avatar Nov 15 '21 07:11 andrewrisse

After applying your proposed solution @Feiyang1 using the custom resolver, the original error TypeError: The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received 'http://localhost/index.node.cjs.js' went away but now I receive the following error:

Cannot find module '@firebase/app' from 'node_modules/firebase/app/dist/index.cjs.js'

    Require stack:
      node_modules/firebase/app/dist/index.cjs.js
      ...

Does anyone else encounter this? The installed "firebase" version is 9.4.0.

Okay I joined in on this and it has been driving me crazy as well, gals and guys I found a working solution. Jest cannot resolve scoped module names correctly sigh so instead you have to add extra rules for the modulenamemapper config to jest. I attempted to use the regex replacer to make a rule, but it did not work as is so I just wrote the rule for each module imported.

"moduleNameMapper": {
      "^@firebase/app$": "<rootDir>/node_modules/@firebase/app/dist/index.cjs.js",
      "^@firebase/component": "<rootDir>/node_modules/@firebase/component/dist/index.cjs.js",
      "^@firebase/logger": "<rootDir>/node_modules/@firebase/logger/dist/index.cjs.js"
    }

This is the final piece of config required for jest along with the original fix to make firebase/app imports work in jest, or at least prevent them from error-ing to allow you to mock the functions inside.

P.S. For anyone using create-react-app you can make almost all of these changes without any issues in the package.json under jest: the only issue is that resolver is not currently an accepted key so it will have to be modified on their end or you will have to fork and add the capability of modifying it which is not a big change tbh but their release cycle is slow enough to make this a wait if we raise the issue and wait for a fix to that separate issue.

MatthewFallon avatar Nov 15 '21 18:11 MatthewFallon

@MatthewFallon, I had to add a few more:

  moduleNameMapper: {
    '^@src/(.*)$': '<rootDir>/src/$1',
    '\\.(css|less|png|jpeg|jpg|svg)$': '<rootDir>/src/__mocks__/mockcss.js',
    '^@firebase/app$': '<rootDir>/node_modules/@firebase/app/dist/index.cjs.js',
    '^@firebase/component': '<rootDir>/node_modules/@firebase/component/dist/index.cjs.js',
    '^@firebase/logger': '<rootDir>/node_modules/@firebase/logger/dist/index.cjs.js',
    '^@firebase/analytics': '<rootDir>/node_modules/@firebase/analytics/dist/index.cjs.js',
    '^@firebase/installations': '<rootDir>/node_modules/@firebase/installations/dist/index.cjs.js'
  },

and

module.exports = (request, options) => {
  // Call the defaultResolver, so we leverage its cache, error handling, etc.
  return options.defaultResolver(request, {
    ...options,
    // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
    packageFilter: (pkg) => {
      if (
        pkg.name.startsWith('@firebase') &&
        !pkg.name.startsWith('@firebase/auth') &&
        !pkg.name.startsWith('@firebase/util') &&
        !pkg.name.startsWith('firebase/auth') &&
        !pkg.name.startsWith('firebase/firestore')
      ) {
        return {
          ...pkg,
          // Alter the value of `main` before resolving the package
          main: pkg.esm5 || pkg.module
        };
      }
      return pkg;
    }
  });
};

Unfortunately I still get the error below and haven't figure out how to resolve it in the same manner:

Cannot find module '../base/dist/emotion-styled-base.cjs.dev.js' from 'node_modules/@emotion/styled/dist/emotion-styled.cjs.dev.js'

andrewrisse avatar Nov 16 '21 06:11 andrewrisse

I think the problem is related to the fact that the @firebase now checked if "document" is defined and changes the loader. I found code that. This createRequire is the thing that next up mapping things to URLs because in jest with jsdom there is a document global even though javascript loading should not be happening through the HTTP connection. image Although I am not seeing the code in the repo under the latest branch https://github.com/firebase/firebase-js-sdk/blob/4d36404812a7ca24ced5e1aabf6d8aa03de4e08a/packages/firestore/src/platform/node/grpc_connection.ts#L43

richtera avatar Nov 16 '21 19:11 richtera

Can someone please try [email protected], and post any issues you encounter? It should fix the The argument 'filename' must be a file URL object error, but I still expect AngularFire users to see some other issues.

Feiyang1 avatar Nov 17 '21 22:11 Feiyang1

@Feiyang1 with [email protected] and none of the above mentioned resolver/mock solutions in place (/all removed again), everything is working as before for me.

sceee avatar Nov 18 '21 06:11 sceee

@Feiyang1 Jest and cypress tests are working using [email protected] and the latest firebase-admin together in the same project.

richtera avatar Nov 19 '21 17:11 richtera