prescottprue / cypress-firebase Goto Github PK
View Code? Open in Web Editor NEWCypress plugin and custom commands for testing Firebase projects
License: MIT License
Cypress plugin and custom commands for testing Firebase projects
License: MIT License
Firstly - this may be a setup problem. My cypress testing files are within a NX workspace, but without cypress-firebase cypress itself runs fine.
The link in the documentation "See the folders section below for more info about other supported folders" doesn't actually go anywhere so I can't check this out.
I have installed the plugin as per the instructions (the NPM instructions are slightly different to the github ones
NPM:
module.exports = (on, config) => { return cypressFirebasePlugin(on, config, admin); };
Github:
module.exports = (on, config) => { const extendedConfig = cypressFirebasePlugin(on, config, admin) return extendedConfig };
For reference my setup is this:
module.exports = (on, config) => { const extendedConfig = cypressFirebasePlugin(on, config, admin) on('file:preprocessor', preprocessTypescript(config)); return extendedConfig; };
I have added a single call to a test that was already working:
cy.callFirestore("add", "test_hello_world", { some: "value" });
And I receive the error cy.callFirestore is not a function
14 | cy.callFirestore("add", "test_hello_world", { some: "value" });
I'm not sure what to try next
I have been receiving "Permission Denied" errors when I add cypress with the following code:
const fbInstance = firebase.initializeApp(CypressConfig.firebase)
if (fbInstance) {
(window as any).fbInstance = fbInstance
}
Here is the full support/index.ts
file:
import * as firebase from "firebase/app"
import "firebase/auth"
import "firebase/database"
import "firebase/firestore"
import attachCustomCommands from "cypress-firebase/lib/attachCustomCommands"
import { CypressConfig } from "../models/config"
const fbInstance = firebase.initializeApp(CypressConfig.firebase)
if (fbInstance) {
(window as any).fbInstance = fbInstance
}
attachCustomCommands({ Cypress, cy, firebase })
import "./login.command"
If I remove the initializeApp, my registration page passes without these errors. But if its in there, then it will fail with over 4-5 permission errors.
Keep in mind that I'm using:
Before submitting this, I wanted to explain what I think it is. Perhaps its because I'm using the same firebase config that I use in my app? Would that be the reason? If not, then I feel its some bug. But I imagine this would have came up in someone else's app. Thoughts?
The following command call should write a single value (456) to users/123ABC/someField
path of Real Time Database:
cy.callRtdb('set', 'users/123ABC/someField', 456)
This currently causes an error
As mentioned in #14 by @fabiocarneiro there is a need for creating user's during tests:
I would like to have it like this:
cy.firebaseSignUp(email, password)
cy.firebaseSignIn(email, password)
other authentication options would also be interesting
Option to return snapshot object when calling callRtdb
or callFirestore
:
cy.callRtdb('get', 'some/data')
.then((dataSnapshot) => {
// dataSnapshot.key
// dataSnapshot.val()
// dataSnapshot.ref
})
cy.callFirestore('get', 'some/data')
.then((dataSnapshot) => {
// dataSnapshot.id
// dataSnapshot.data()
// dataSnapshot.metadata
})
If there's a better forum to bring this up in, please let me know.
I have configured the Firestore and Functions emulators locally. My React UI is working against them just fine. But my cy.callFirestore()
methods are still hitting my actual FS database in my Firebase console.
I have run out of ideas to try for configuring the cy commands. I have followed the Using Database Emulators instructions line by line. My console.log() statements show me that firebase.firestore().settings({ host: localhost:5002 })
is being called. I don't see any errors in the logs. I started looking at the FirestoreClient code, but am not sure how best to go about debugging that (if possible by mere mortals).
Thoughts/suggestions?
Thanks!
Is it possible to add support for Firestore emulator?
Your plugin is great. It save me a lot of time with my Cypress testing. I have a need to access the Firebase Admin tool from my testing. Basically, I want to verify user are created correctly, for now. Are you interested in expanding this plugin? If so, I would like to help.
Hello,
when I try to update a document in firestore it's not updated and an error occurs with the following message:
update() requires either a single javascript object or an alternating list of field/value pairs
This is probably due to the fact that the data for update is not passed in the corresponding command:
I tested it locally by passing the fixturePath as a third argument and it seems to be working as expected.
Let me know what you think. I'd happily submit a fix for this.
Thanks,
Bettina
Does the framework support login via different users?
I have several roles in my app and I want to test each one of them.
Can I declare on different TEST_UIDs in the config in use different users in the tests or there is a workaround for this?
I'm running locally with a user that can authenticate. I can login with that user and initiate firestore listeners without issue. However, when I do so via cypress I'm getting the following error.
FirebaseError: Missing or insufficient permissions. at new FirestoreError
I know I have the Firestore rules are set properly because I have multiple users that work and my test user also works if I'm not using cypress.
Here an example of the listener code. It's likely not very helpful as it's basically what you would see in the docs.
db.doc(`users/${firebaseUser.uid}`).onSnapshot(
doc => {
const data = doc.data()
if (!doc.exists) {
user = null
}
console.log('worked')
},
err => {
// This is where it's catching
console.error(err)
}
)
I have two event listeners similar to this. Something that is a bit odd about this is that one listener will succeed and then fail while the second will always fail.
Have you used this with Firestore listeners before?
Have you had to do anything with the Firestore rules to enable this specifically with Cypress?
Any other ideas?
When using a custom integration folder, building testConfig fails as follows:
❯ yarn build:testConfig
$ cypress-firebase createTestEnvFile
✖ Error: Test env file could not be created:
STAGE_TEST_UID is missing from environment. Confirm that tests/e2e/integration/config.json contains either STAGE_TEST_UID or TEST_UID.
cypress.json:
{
"projectId": "blah",
"pluginsFile": "tests/e2e/plugins/index.js",
"integrationFolder": "tests/e2e/integration/",
"screenshotsFolder": "test/e2e/screenshots/",
"videosFolder": "test/e2e/videos/",
"supportFile": "test/e2e/support/index.js",
"fixturesFolder": "test/e2e/fixtures/"
}
I'm having issues setting environment variables for firebase on CI/CD (github actions). The README mentions createTestEnv
at the top of the file. createTestEnv
appears to be a command passed to a command line script ($> cypress-firebase createTestEnv
).
However, I can't actually find this script, and I find instructions for it in previous versions of this repo. I did find instructions on setting the CYPRESS_TEST_UID and SERVICE_ACCOUNT environment variables, however that has not made a difference as far as I can tell.
Any advice on how I can use this plugin in CI/CD?
I assume it's something missing while i follow along the doc, so i can not add test data to Firestore.
Plus, I checked my Firestore rule that allows write with everyone(bad, but just for testing for now.).
Please try to help us.
Thanks
CypressError: cy.exec('$(npm bin)/firebase-extra firestore add axatest/HUD9SxZHjmrBkGFo5Fl6') failed because the command exited with a non-zero code.
Pass {failOnNonZeroExit: false} to ignore exit code failures.
Information about the failure:
Code: 1
Stderr:
Error running firebase action: Ref at provided path "axatest/HUD9SxZHjmrBkGFo5Fl6" does not have action "add"
cypress-firebase assumes hard-coded locations for the cypress.json file among other files. vue-cli extension for cypress places the files in a different base location that is assumed by this module. Is there a way that I can customize, or pass the location of the files needed for this module to work?
I could fork and make the changes if you have suggestions on how you'd approach fixing file paths.
The functions which should be attached to the cy
object are not available:
cy.login is not a function
Also other functions which should be attached to the plugin are not there.
Taking first steps on Cypress, I followed the setup guide.
I am using a createReactApp based setup now, so I also followed the example, but this seems to be somewhat outdated: cypress-firebase createTestEnvFile
fails
You can check out the branch in my repo and execute cypress.
Remark: I removed the FB config in the commands before pushing it.
I'm quite sure the issue is on my end and my understanding.
The library looks well architectured and understandable, but I couldn't get it working during the past four hours.
The ability to call a Cloud Function would be powerful.
A key benefit would be the ability to do "administrative functions" via those cloud functions. Say, for example, deleting all existing users in a Firebase project. Possibly related to #88 .
https://firebase.google.com/docs/functions/callable#call_the_function
I'm trying to setup a firebase cypress test but after following the readme I'm getting the following error:
Error: Your API key is invalid, please check you have copied it correctly.
I copied and paste the value of the 'apiKey' property of the firebase project multiple times so I should be using the correct key. Would you happen to have any other insights into what's going on?
I wanted to use this package but unfortunately I can't get it working with lerna monorepo / yarn workspaces.
Problem is that I have .firebaserc
file stored in root
of my project (so it's available to web, mobile and functions project files), but my web application lives in packages/web
.
It doesn't matter if I run cyrpess from packages/web folder (via cypress open
) or from root folder (via cypress open --project packages/web
), command always fails with exception:
Here is the exception being thrown:
We invoked the function exported by packages\web\cypress\plugins\index.js, but it threw an error.
Error: .firebaserc file not found
at loadFirebaseRc (node_modules\cypress-firebase\lib\extendWithFirebaseConfig.js:15:15)
at getFirebaseProjectIdFromConfig (node_modules\cypress-firebase\lib\extendWithFirebaseConfig.js:42:28)
at extendWithFirebaseConfig (node_modules\cypress-firebase\lib\extendWithFirebaseConfig.js:74:31)
at module.exports (packages\web\cypress\plugins\index.js:23:10)
at Local\Cypress\Cache\4.0.2\Cypress\resources\app\packages\server\lib\plugins\child\run_plugins.js:77:1
I tried to follow along the Readme, and got the first few steps working. I can confirm that my integration works, since the firestore document example is working.
However, when I try to add cy.login()
to my test hooks, I get this error
This is my test file.
describe('Hooks', () => {
before(() => {
cy.login();
});
it('Runs', () => {
cy.viewport('iphone-x');
cy.visit('https://dev.estockx.com/');
});
});
I have tried all three methods of adding the userId as explained in the readme, but none seem to work.
What am I missing?
I checked cypress-firebase 0.4.0 with node 10 and node 12 and IMHO your application has a problem with node 12. I got this error
NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
in my application when I used only node 12. When I used node 10 everything was perfect
My all dependencies (I checked cypress: 3.4.1/3.5.0/3.6.0):
"dependencies": {
"@angular/animations": "^8.0.0",
"@angular/cdk": "~8.0.2",
"@angular/common": "^8.0.0",
"@angular/compiler": "^8.0.0",
"@angular/core": "^8.0.0",
"@angular/fire": "^5.2.1",
"@angular/flex-layout": "^8.0.0-beta.27",
"@angular/forms": "^8.0.0",
"@angular/material": "~8.0.2",
"@angular/platform-browser": "^8.0.0",
"@angular/platform-browser-dynamic": "^8.0.0",
"@angular/pwa": "^0.13.8",
"@angular/router": "^8.0.0",
"@angular/service-worker": "^8.0.0",
"@auth0/angular-jwt": "^2.1.0",
"@fortawesome/angular-fontawesome": "^0.4.0",
"@fortawesome/fontawesome-free": "^5.8.1",
"@fortawesome/fontawesome-svg-core": "^1.2.19",
"@fortawesome/free-regular-svg-icons": "^5.9.0",
"@fortawesome/free-solid-svg-icons": "^5.9.0",
"@ngrx/effects": "^8.0.1",
"@ngrx/entity": "^8.0.1",
"@ngrx/router-store": "^8.0.1",
"@ngrx/store": "^8.0.1",
"@ngrx/store-devtools": "^8.0.1",
"@nrwl/angular": "8.7.0",
"angular-in-memory-web-api": "0.8.0",
"chart.js": "^2.8.0",
"core-js": "^2.5.4",
"date-fns": "^2.0.1",
"date-fns-timezone": "^0.1.4",
"firebase": "^6.3.1",
"firebase-admin": "^8.3.0",
"firebase-functions": "^3.2.0",
"hammerjs": "^2.0.8",
"jq": "^1.7.2",
"lodash": ">=4.17.11",
"logrocket": "^0.6.20",
"logrocket-ngrx": "^0.1.1",
"ng2-charts": "^1.5.0",
"ngx-sortablejs": "^3.1.3",
"primeng": "^8.0.1",
"quill": "^1.3.6",
"rxjs": "^6.5.2",
"sortablejs": "^1.9.0",
"truncate-html": "^1.0.2",
"tsify": "^4.0.1",
"uuid": "^3.3.3",
"zone.js": "^0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.803.3",
"@angular/cli": "8.3.15",
"@angular/compiler-cli": "^8.0.0",
"@angular/language-service": "^8.0.0",
"@ngrx/schematics": "^8.0.1",
"@nrwl/cypress": "8.7.0",
"@nrwl/jest": "8.7.0",
"@nrwl/node": "8.7.0",
"@nrwl/workspace": "8.7.0",
"@types/faker": "^4.1.4",
"@types/jest": "24.0.9",
"@types/node": "~8.9.4",
"codelyzer": "~5.0.1",
"concurrently": "^4.1.2",
"cypress": "^3.6.0",
"cypress-firebase": "^0.4.0",
"cypress-pipe": "^1.5.0",
"dotenv": "6.2.0",
"eslint": "6.1.0",
"faker": "^4.1.0",
"firebase-functions-test": "^0.1.6",
"firebase-tools": "^6.10.0",
"git-describe": "^4.0.4",
"husky": "^1.3.1",
"jest": "24.9.0",
"jest-preset-angular": "7.0.0",
"ng-mocks": "8.0.0",
"prettier": "1.16.4",
"rxjs-tslint-rules": "^4.14.3",
"ts-jest": "24.0.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.5.3"
}
Do you have the same problem? Could you fix it?
Hi,
I'm running into an error when I call the callRtdb function. I've setup cypress firebase with create-react-app as per the instructions in the examples. However, when I run the following test:
describe("first test", () => {
it("works", () => {
cy.login();
cy.callRtdb("remove", `managers/${Cypress.env("TEST_UID")}`)
cy.visit("/");
});
});
I get the following error:
CypressError: cy.exec('$(npm bin)/firebase database:remove /managers/xxxx -P firebase-app-id -y') failed because the command exited with a non-zero code.
Pass {failOnNonZeroExit: false} to ignore exit code failures.
Information about the failure:
Code: 127
Stderr:
zsh:1: no such file or directory: /Users/Richard/Code/premier-manager/node_modules/.bin/firebase
First of all, I tried to pass in the {failOnNonZeroExit: false}
with no difference in the error. I've since focussed on the Stderr:
. I can see firebase is a node module however there is no firebase
file in the .bin
directory. Does this need to be generated?
Any help would be appreciated!
I'm trying to create unit tests with Cypress on a Vue project but keep getting an error:
Error: Webpack Compilation Error
./node_modules/cypress-firebase/lib/node-utils.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\johan\VueProjects\paddock-app\node_modules\cypress-firebase\lib'
cypress-io/cypress-documentation#714 says fs is not to be used in cypress as it is sitting in the browser. How do I go about avoiding this webpack compilation issue?
I've been trying to run cypress-firebase on CI, but keep getting this error:
✖ Error: STAGE_FIREBASE_PRIVATE_KEY not found, make sure it is set within environment variables.
✖ Error: Test env file could not be created:
Service Account is missing parameters: private_key_id, private_key, client_email, client_id, client_x509_cert_url
I tried different things:
none of them works.
I want to add object to the firebase/firestore with null value
newObject = {
name: 'new object',
finishDate: null
}
I've used this function:
cy.callFirestore("set", "task", newObject );
I've got an error in the bold part of the below code (src/tasks.ts:80):
if (
typeof data[currKey] === 'object' &&
/* eslint-disable-next-line no-underscore-dangle */
!data[currKey]._methodName &&
!data[currKey].seconds &&
!Array.isArray(data[currKey])
)
Because currKey is set to 'finishDate' and date[finishDate] is null and data[currKey]._methodName throws an error.
IMHO it is a regression bug because I got this error after update from 1.0 to 1.4.2.
Is it a bug? Could you fix it?
I would like to test your plugin, but we already have custom commands like cy.login, cy.register and cy.logout. These names are very common.
It would be nice if the commands for this plugin would be prefixed, like cy.firebaseLogin
, this also describes the use case better.
I tried calling:
cy.callFirestore("update", "companies/my-id", { creditsRemaining: 1000 })
and
cy.callFirestore("set", "companies/my-id", { creditsRemaining: 1000 })
But receive this error:
Error: the string "(node:25288) UnhandledPromiseRejectionWarning: Error: Fixture not found at path: test\\e2e\\fixtures\\'{creditsRemaining:1000}' or cypress\\fixtures\\'{creditsRemaining:1000}'\n at readFixture (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\firebase-tools-extra\\lib\\commands\\firestore.js:26:19)\n at C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\firebase-tools-extra\\lib\\commands\\firestore.js:96:39\n at step (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\tslib\\tslib.js:136:27)\n at Object.next (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\tslib\\tslib.js:117:57)\n at C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\tslib\\tslib.js:110:75\n at new Promise (<anonymous>)\n at Object.__awaiter (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\tslib\\tslib.js:106:16)\n at firestoreAction (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\firebase-tools-extra\\lib\\commands\\firestore.js:87:20)\n at runFirebaseExtra (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\firebase-tools-extra\\bin\\firebase-tools-extra:57:12)\n at Object.<anonymous> (C:\\Users\\I20649\\Workspace\\testramp-ng8\\node_modules\\firebase-tools-extra\\bin\\firebase-tools-extra:66:2)\n(node:25288) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:25288) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code." was thrown, throw an Error :)
Because this error occurred during a 'before all' hook we are skipping the remaining tests in the current suite: 'Client New Test Run Page'
It looks like it won't allow an object like your documentation states:
cy.callFirestore('set', `testCollection/${TEST_UID}`, {
name: 'axa',
age: 8,
})
Versions:
cypress-firebase: "0.4.1"
cypress: "3.4.1"
firebase-tools: "^7.8.0"
This seems like a bug.
The application I am currently trying to test is built on auth0 for authentication and uses a Firestore backend. Auth0 authentication is done completely separately from anything relating to Firestore, so first we do that and it is working fine.
Using cypress-firebase we are able to seed data in the Firestore instance using the custom commands cy.callFirestore()
and all methods work including delete. In the process of running the tests though, and after some troubleshooting, we have found out that window.fbInstance
is undefined. So the Firestore instance we have set up is never attached to the window so the application under test never gets connected to it. Our configure-store.js
is set up the same way as your gist here too.
Currently, I am not using cy.login()
in my tests, but that does not seem like the solution to this problem. It has it's own problem when using cy.login()
though where I get an error message saying the API key is invalid, but is the same from the FIrestore instance.
@prescottprue do you have an example application of all of this working with a Firestore backend?
- Make sure to set CYPRESS_TEST_UID environment variable in your CI settings if you are running tests in CI
- Call cy.login() with the before or beforeEach sections of your tests
Not clear how these relate to the Setup, or if these are starting to talk more about usage once the system is up? Maybe these could/should be moved to a separate section away from "Setup", like maybe a separate "Considerations for CI" section?
A request: at the end of the Setup section have a step that "confirms things are working" ? Even if that was a simple Recipe that requires additional tools (e.g. a default Cypress setup, a simple example script), it would be a huge help in getting people started.
For newbies (me!), I fear overloading the section meant to just "get things up and started". I feel like I'm being led into deeper areas before I know that the basics are in place. (And maybe this is just me not having captured enough knowledge of all the moving parts yet...)
Hi there,
first, thanks for the project, it helped me a lot!
Unfortunately I have an issue when using cy.logout
.
I have tests with cy.login()
in the Cypress before
hook, those work great.
But I also want to test the logged out state, so I defined cy.logout()
in the before
hook accordingly. Those tests fail on the cy.logout()
command with the following:
Error: CypressError: Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.
The command that returned the promise was:
> cy.logout()
The cy command you invoked inside the promise was:
> cy.log()
Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise.
Cypress will resolve your command with whatever the final Cypress command yields.
The reason this is an error instead of a warning is because Cypress internally queues commands serially whereas Promises execute as soon as they are invoked. Attempting to reconcile this would prevent Cypress from ever resolving.
https://on.cypress.io/returning-promise-and-commands-in-another-command
Because this error occurred during a 'before all' hook we are skipping the remaining tests in the current suite: 'Landing Page Unauthenticated'
I'm not sure if this is an issue on my side (wrong usage,...) or something of the lib.
For reference you can find the code of the failing test here.
Thanks for your help!
-Alex
Hi @prescottprue,
Using the following command to set an object with a timestamp property i.e.:
cy.callFirestore(
'set',
`buildings/${BUILDING_ID}/parcels/${TEST_PARCEL_ID}`,
{
timeOfArrival: firestore.FieldValue.serverTimestamp(),
}
);
Results in:
{
timeOfArrival: { _methodName: 'FieldValue.serverTimestamp' } (string)
} (Map)
I've done a bit of investigating and it looks like there's possibly a know issue with cy.task stringifying and parsing the data which could be related:
Is there anything with the library that would help with or is it possible to work around the issue somehow?
I've crudely messed around in the tasks.js and got it working for my example but it's not something good enough to be a fix but I thought I'd include it incase it was useful:
if (action === 'set') {
Object.keys(data).forEach(key => {
if (data[key] && data[key]._methodName && data[key]._methodName === 'FieldValue.serverTimestamp') {
data[key] = adminInstance.firestore.FieldValue.serverTimestamp()
}
})
return adminInstance
.firestore()
.doc(actionPath)[action](data, (options === null || options === void 0 ? void 0 : options.merge) ? { merge: options === null || options === void 0 ? void 0 : options.merge } : undefined)
.catch(handleError);
}
Let me know if I can provide anything more useful! Thanks in advance for any help and for the lib!
When using the callFirestore('delete')
command, is there currently a way to pass the firebase token generated from firebase-tools login:ci
as an option? Currently the command looks as though passing an options object does nothing as the passed in object is ignored while a new one is created with Cypress and args arguments: const deleteArgsWithDefaults = addDefaultArgs(Cypress, args);
In my specific use case I am attempting callFirestore('delete', 'actionPath/in/Firestore', { '--token', Cypress.env.FIREBASE_TOKEN }
but the options object is being dropped and the console output when the call fails is as follows:
CypressError: cy.exec('$(npm bin)/firebase firestore:delete actionPath/in/Firestore -P -y --shallow') failed because the command exited with a non-zero code.
So the options object { --token, Cypress.env.FIREBASE_TOKEN }
is being ignored for the favored default arguments. If it helps at all, I think the line in question is in buildFirestoreCommand.js
with the line const deleteArgsWithDefaults = addDefaultArgs(Cypress, args);
which creates a brand new object instead of building on the one that was passed in.
In README.md, the section:
There is an imcomplete thought at the "[...]" below:
SERVICE_ACCOUNT - service account object and the [...]
Thanks very much for this library. The instructions suggest that I must include a serviceAccount.json
file in the root. I was keen to avoid this, as we have the same information saved under a different file name in a different directory, for use in other tests.
If I could point cypress-firebase to the information from this file, this would save us having two copies of the same information in two places (and save devs copying the file twice).
I think I've been able to achieve this, so thought I'd check I'm doing the right thing. If I am, perhaps this could be added to the documentation in case others have the same use case.
It required this change to plugins/index.js
, at step 7 in the README.md.
// plugins/index.js
const admin = require('firebase-admin');
const cypressFirebasePlugin = require('cypress-firebase').plugin;
module.exports = (on, config) => {
// This is my abcde.firebaseio.com URL. An env variable but could just be inline.
const firebaseURL = config.env.FIREBASE_DB_URL;
// This is the path of my `serviceAccount.json` file, relative to the `plugins` folder. An env variable but could just be inline.
const firebaseKeyPath = config.env.FIREBASE_SERVICE_ACCOUNT_KEY;
// Import the json file using this path
const serviceAccount = require(firebaseKeyPath);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: firebaseURL,
});
// Below this point is the same as in README.md
const extendedConfig = cypressFirebasePlugin(on, config, admin);
return extendedConfig;
};
It helps me a lot to test the firebase project. Thanks.
But, cy.logout() don't run correctly.
In logout command, you use 'firebase.auth().currentUser'.
The official document says currentUser might also be null because the auth object has not finished initializing.
https://firebase.google.com/docs/auth/web/manage-users?hl=en#get_the_currently_signed-in_user
So, it is better to use onAuthStateChanged method, as your login command.
On my (new MacOS) system that (I'm trying to leave as clean as reasonable and possible), I get:
$ npm run test:emulate
> [email protected] test:emulate /Users/greg/work/react-firebase-auth-and-profile
> cross-env FIREBASE_DATABASE_EMULATOR_HOST="localhost:$(cat firebase.json | jq
.emulators.database.port)" FIRESTORE_EMULATOR_HOST="localhost:$(cat firebase.json | jq
.emulators.firestore.port)" yarn test:open
sh: jq: command not found
The test:emulate script depends on both jq
and yarn
.
jq I get and can live with (brew install jq
), but just about everything else on this project uses npm rather than yarn.
Didn't want to submit a PR for this change without a discussion :)
Thank you @prescottprue for such a useful package. A few questions regarding the configuration of cypress-firebase
with CircleCI. I referenced issue #23 which helped me get to where I am now.
As a note, I have am using your package perfectly in my local environment. The command I'm using is essentially, yarn run build:testConfig && cypress run
where build:testConfig
is cypress-firebase createTestEnvFile
First, I'm hoping you can clarify that these logs in CircleCI prove that I my SERVICE_ACCOUNT
environment variable is properly accessible:
$ cypress-firebase createTestEnvFile
ℹ Service account does not exist at path: "serviceAccount.json" falling back to environment variables...
ℹ Generating custom auth token for Firebase project with projectId: auth-core-api
✔ Custom token generated successfully, writing to cypress.env.json
✔ cypress.env.json updated successfully
It looks like cypress-firebase
was able to create a an auth token with the SERVICE_ACCOUNT
env variable. Is that correct?
But then immediately after I get the following error:
[03:34:49] Verifying Cypress can run /root/.cache/Cypress/4.1.0/Cypress [started]
[03:34:51] Verifying Cypress can run /root/.cache/Cypress/4.1.0/Cypress [completed]
Opening Cypress...
Fontconfig warning: "/etc/fonts/fonts.conf", line 100: unknown element "blank"
ℹ Service account does not exist at path: "serviceAccount.json" falling back to environment variables...
Initialized with Service Account for project "auth-core-api"
Recording this run failed because the request was invalid.
Request should follow [email protected] schema
Errors:
[
"data.projectId must be projectId format"
]
I'm not sure where to go from here with data.projectId
and postRunRequest
. For further context, I'm using version ^0.11.0
of cypress-firebase
. Thanks in advance for any guidance.
error trace
cypress_runner.js:172390 Error: the string "(node:5185) UnhandledPromiseRejectionWarning: Error: 4 DEADLINE_EXCEEDED: Deadline Exceeded\n at Object.exports.createStatusError (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/grpc/src/common.js:91:15)\n at Object.onReceiveStatus (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/grpc/src/client_interceptors.js:1204:28)\n at InterceptingListener._callNext (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/grpc/src/client_interceptors.js:568:42)\n at InterceptingListener.onReceiveStatus (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/grpc/src/client_interceptors.js:618:8)\n at callback (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/grpc/src/client_interceptors.js:845:24)\n(node:5185) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)\n(node:5185) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code." was thrown, throw an Error :)
at Runner.fail (cypress_runner.js:51724)
at Runner.fail (cypress_runner.js:81207)
at cypress_runner.js:52042
at next (cypress_runner.js:82124)
at cypress_runner.js:82136
at tryCatcher (cypress_runner.js:132142)
at Promise._settlePromiseFromHandler (cypress_runner.js:130160)
at Promise._settlePromise (cypress_runner.js:130217)
at Promise._settlePromise0 (cypress_runner.js:130262)
at Promise._settlePromises (cypress_runner.js:130341)
at Promise._fulfill (cypress_runner.js:130286)
at Promise._resolveCallback (cypress_runner.js:130080)
at Promise._settlePromiseFromHandler (cypress_runner.js:130172)
at Promise._settlePromise (cypress_runner.js:130217)
at Promise._settlePromise0 (cypress_runner.js:130262)
at Promise._settlePromises (cypress_runner.js:130341)
my devdependencies
:
"dependencies": {
"@octokit/rest": "^15.8.2",
"@typeform/embed": "^0.8.1",
"axios": "^0.18.0",
"blueimp-md5": "^2.10.0",
"brace": "^0.11.1",
"classnames": "^2.2.5",
"firebase": "^5.0.4",
"material-ui": "^1.0.0-beta.34",
"material-ui-icons": "^1.0.0-beta.17",
"prismjs": "^1.16.0",
"prop-types": "^15.6.0",
"query-string": "^6.2.0",
"react": "^16.4.0",
"react-ace": "^7.0.1",
"react-dom": "^16.4.0",
"react-ga": "^2.4.1",
"react-hot-loader": "^4.3.1",
"react-hotjar": "^2.0.0",
"react-intl": "^2.4.0",
"react-redux": "^5.0.7",
"react-redux-firebase": "2.2.4",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^4.0.8",
"recompose": "^0.30.0",
"redux": "^4.0.0",
"redux-firestore": "^0.5.6",
"redux-thunk": "^2.3.0"
},
I need to say this error just happens sometimes rarely.
Hi, thank you for your great work. I'm succesfully authenticating with your library, but get the following error when I'm trying to connect to the realtime firebase database:
Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
I tried it with this script:
describe("Account Page", () => {
before(() => {
cy.login()
cy.visit("/settings")
})
it("Should save to Database", () => {
const fakeProject = { some: "data" }
cy.callRtdb("set", "projects/ABC123", fakeProject)
})
And already set the enviroment variable for testing in the scripts like:
Cypress.env({
NODE_TLS_REJECT_UNAUTHORIZED: "0"
})
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
and in the .bash_profile:
export NODE_TLS_REJECT_UNAUTHORIZED=0
But I couldn't get it to work. Do you have an clue?
Thank you in advance!
I have been needing the ability to update the FIREBASE_AUTH_JWT (calling createTestEnvFile) during a test. I think the best way to do this is the move the createTestEnvFile into a task. This would allow us to still use node.js, but still have all the functionality there. Can this be possible?
I get the following when following the README instructions and starting cypress:
**Message:** The function exported by the plugins file threw an error.
**Details:** Error: Error GCLOUD_PROJECT environment variable or project_id from service account to initialize Firebase.
Any ideas?
When I import cypress-firebase into my Cypress project, using Typescript, I receive the following error:
./node_modules/cypress-firebase/lib/utils.js
Module not found: Error: Can't resolve 'child_process' in 'C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\lib'
resolve 'child_process' in 'C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\lib'
...
./node_modules/cypress-firebase/lib/utils.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\lib'
resolve 'fs' in 'C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\lib'
Parsed request is a module
using description file: C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\package.json (relative path: ./lib)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\lib\node_modules doesn't exist or is not a directory
C:\Users\I20649\Workspace\testramp\node_modules\node_modules doesn't exist or is not a directory
C:\Users\I20649\node_modules doesn't exist or is not a directory
C:\Users\node_modules doesn't exist or is not a directory
C:\node_modules doesn't exist or is not a directory
looking for modules in C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules
using description file: C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\package.json (relative path: ./node_modules)
Field 'browser' doesn't contain a valid alias configuration
looking for modules in C:\Users\I20649\Workspace\testramp\node_modules
using description file: C:\Users\I20649\Workspace\testramp\package.json (relative path: ./node_modules)
Field 'browser' doesn't contain a valid alias configuration
using description file: C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\package.json (relative path: ./node_modules/fs)
no extension
Field 'browser' doesn't contain a valid alias configuration
using description file: C:\Users\I20649\Workspace\testramp\package.json (relative path: ./node_modules/fs)
no extension
Field 'browser' doesn't contain a valid alias configuration
looking for modules in C:\Users\I20649\Workspace\node_modules
No description file found
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs doesn't exist
.ts
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\testramp\node_modules\fs doesn't exist
.ts
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs.ts doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\testramp\node_modules\fs.ts doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs.js doesn't exist
C:\Users\I20649\Workspace\testramp\node_modules\fs.js doesn't exist
No description file found
no extension
Field 'browser' doesn't contain a valid alias configuration
as directory
C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs doesn't exist
as directory
C:\Users\I20649\Workspace\testramp\node_modules\fs doesn't exist
C:\Users\I20649\Workspace\node_modules\fs doesn't exist
.ts
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\node_modules\fs.ts doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
C:\Users\I20649\Workspace\node_modules\fs.js doesn't exist
as directory
C:\Users\I20649\Workspace\node_modules\fs doesn't exist
[C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\lib\node_modules]
[C:\Users\I20649\Workspace\testramp\node_modules\node_modules]
[C:\Users\I20649\node_modules]
[C:\Users\node_modules]
[C:\node_modules]
[C:\Users\I20649\Workspace\node_modules\package.json]
[C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs]
[C:\Users\I20649\Workspace\testramp\node_modules\fs]
[C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs.ts]
[C:\Users\I20649\Workspace\testramp\node_modules\fs.ts]
[C:\Users\I20649\Workspace\testramp\node_modules\cypress-firebase\node_modules\fs.js]
[C:\Users\I20649\Workspace\testramp\node_modules\fs.js]
[C:\Users\I20649\Workspace\node_modules\fs\package.json]
[C:\Users\I20649\Workspace\node_modules\fs]
[C:\Users\I20649\Workspace\node_modules\fs.ts]
[C:\Users\I20649\Workspace\node_modules\fs.js]
@ ./node_modules/cypress-firebase/lib/utils.js 1:1057-1070
@ ./node_modules/cypress-firebase/lib/buildRtdbCommand.js
@ ./node_modules/cypress-firebase/lib/attachCustomCommands.js
@ ./cypress/support/index.ts
@ multi ./cypress/support/index.ts
I have already figured out why. For some reason, when importing it through Typescript, cypress-firebase will import utils.js, which has the fs module, but cypress/support/index does not allow it. I found a way to fix this, and have done this locally as a test, but I would much rather have this fixed in your module, so I can help support this module, as well.
To fix this, I moved only the necessary functions in the utils (FIREBASE_TOOLS_BASE_COMMAND
, FIREBASE_EXTRA_PATH
, addDefaultArgs
, getArgsString
) and moved them into another file (lets say support-utils.js
). And then I keep the rest of utils, as it is. Then for buildRtdbCommand.js
and buildFirestoreCommand.js
will only reference support-utils.js
. Once I did this, and added the proper d.ts
files to my project, your code worked! But I want to stay current and contribute to this library.
The last thing that would need to happen is to have two imports:
cypress-firebase/support
and
cypress-firebase/plugin
The reason this occurs is because extendWithFirestoreConfig also has the fs module. So separating the imports into both of these would makes it work for me. Then in support/index.ts, I would import:
import cypressFirebasePlugin from "cypress-firebase/plugin"
and plugins/index.js (since even in typescript, it needs to be a js file):
import attachCustomCommands from "cypress-firebase/support"
I have not yet made a PR since this is a lot of changes. Would this be feasible?
In createTestEnvFile.js add support for using custom developer claims to your Firebase instance, building on existing isTesting claim.
This plugin is great and I think it will save me and my team a lot of time in testing. This is a feature I need in a timely manner so I may have a PR coming your way on it :)
Hi,
In 0.0.8 I set my TEST_UID in config.json which I stored in $PROJECT_ROOT/cypress/config.json.
In 0.1.0 the library appears to be looking for the config file in $PROJECT_ROOT/config.json.
I think you can see this in the new file filepaths.js that sets the location
cypress-firebase/src/filePaths.js
Line 22 in d7a8439
I think this is unintentional because a new section of the docs describes setting the config directory by using a new integrationFolder property in cypress.json
https://github.com/prescottprue/cypress-firebase/blob/master/README.md#folders
What do you think? If you want me to then I'm happy to open a PR either way. (Either to update the file locations to use the integrationsFolder property or to update the README)
Also happy to hear if the issue is a misconfiguration on my part!
Thanks for the library!
Is there a provision for an alternative to serviceAccount.json
since it can't possibly be checked in to VC to be used in the CI? There are some CI variables stated in the readme, but they only apply to other firebase tools used by the library.
I have a simple test to validate authentication.
describe('authentication', () => {
before(() => {
cy.visit('/')
// Login using custom token
cy.login()
})
after(() => {
// disable this to see the page after login
cy.logout()
})
it('should login', () => {
cy.get('title#logoWithName').should('contain', 'Keepify')
})
})
I get the following error while running cypress and my app locally as well as when running cypress locally and pointing at my actual instance firebase instance.
Error: The custom token format is incorrect. Please check the documentation.
I've created a new private key using a service account and saved it as serviceAccount.json
as well as everything else outlined in the setup section. Everything looks like it should be working. I've validated the JWT generated on https://jwt.io/.
If I login manually then it works hitting the firebase.auth().currentUser
- ('Authed user already exists, login complete.')
use case but that doesn't test the token case - signInWithCustomToken
.
Development Platform:
Windows 10
Git Bash shell
"Error with set at path "cohorts/lim-2019-07-pre-core-admission": Error: @grpc/grpc-js only works on Node ^8.13.0 || >=10.10.0
at Object.<anonymous> (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/@grpc/grpc-js/build/src/index.js:45:11)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/google-gax/build/src/grpc.js:37:14)
at Module._compile (module.js:653:30)
(node:25453) ExperimentalWarning: The http2 module is an experimental API.
(node:25453) UnhandledPromiseRejectionWarning: Error: @grpc/grpc-js only works on Node ^8.13.0 || >=10.10.0
at Object.<anonymous> (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/@grpc/grpc-js/build/src/index.js:45:11)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/home/raulingg/Projects/laboratoria/admission.laboratoria.la/node_modules/google-gax/build/src/grpc.js:37:14)
at Module._compile (module.js:653:30)
(node:25453) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:25453) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code."
my package.json
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.0.1",
"babel-loader": "^7.1.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^0.1.18",
"cross-env": "^5.2.0",
"css-loader": "^0.28.9",
"cypress": "^3.3.1",
"cypress-firebase": "^0.2.0",
"dotenv-webpack": "^1.7.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.18.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-babel": "^5.3.0",
"eslint-plugin-chai-friendly": "^0.4.1",
"eslint-plugin-cypress": "^2.2.1",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.6.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"favicons-webpack-plugin": "^0.0.9",
"file-loader": "^1.1.7",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"husky": "^2.4.1",
"jest": "^23.1.0",
"minimist": "^1.2.0",
"mocha": "^5.2.0",
"mochawesome": "^4.0.1",
"mochawesome-merge": "^2.0.1",
"mochawesome-report-generator": "^4.0.0",
"uglifyjs-webpack-plugin": "^1.2.0",
"url-loader": "^1.0.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.4",
"webpack-dev-server": "^3.1.4"
}
I need to say that it works fine with the previous version.
When using the callFirestore()
function and passing a fixture path as third argument, the path to the fixture is being appended to the full path with double quotes.
So I am trying to set some data in the database from my fixture path featureFlags/someFeatureFlag.json
which is in my project at this file path: test/e2e/fixtures/
but I am receiving the error Error running firebase action: Fixture not found at path: test/e2e/fixtures/"featureFlags/someFeatureFlag.json" or cypress/fixtures/"featureFlags/someFeatureFlag.json"
.
I cannot find where in the code this string is being appended to the file path that is being searched, otherwise I would already have a PR out for this 😝
I have installed code-coverage for Cypress.
My test against my app work just fine. But my tests that call cy.callFirestore()
fail with:
cy.task('callFirestore') failed with the following error:
The task 'callFirestore' was not handled in the plugins file. The following tasks are registered: resetCoverage, combineCoverage, coverageReport
Fix this in your plugins file here:
/Users/merpy/work/tick8s/cypress/plugins/index.js
If I disable the code-coverage configuration in Cypress, the cy.callFirebase()
tests works just fine.
It seems there is a need to expose callFirestore
to the "code instrumentation" process. This might be a fairly straight-forward thing, but I'm not sure how best to do it in a create-react-app built app that is using cypress-firesbase. Again, my other tests (all pure cypress API) work just fine.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.