Coder Social home page Coder Social logo

quickstart-testing's Introduction

Firebase Testing Quickstarts

A collection of quickstart samples demonstrating testing patterns for Firebase services.

The repository is broken up by testing strategy:

How to make contributions?

Please read and follow the steps in the CONTRIBUTING.md

License

See LICENSE

Build Status

Actions Status

quickstart-testing's People

Contributors

davideast avatar dependabot[bot] avatar dpebot avatar gavingolden avatar jorisphilipsen avatar kognise avatar kroikie avatar markarndt avatar n0mer avatar nothingeverhappens avatar rubiagatra avatar samtstern avatar thatfiredev avatar vvmnnnkv avatar yuchenshi avatar zeroasterisk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quickstart-testing's Issues

Testing with AppCheck

I am trying to unit test my callable cloud functions but I ran into the problem that due to AppCheck the test will always fail. Is there an example on how to integrate AppCheck into unit testing? Could you update your examples to reflect the integration of AppCheck? Guess this should be relevant for a lot of people since AppCheck is now being used more often.

Testing firestore rules against emulator fails with reason: Unexpected token < in JSON at position 0

Hi, I am trying to setup firestore rules unit tests.

Since I am using typescript and jest for testing, I have edited your provided example a bit. This is what I have currently:

import { readFileSync } from 'fs-extra'
import * as firebase from '@firebase/rules-unit-testing'
import { getDoc, setDoc, setLogLevel } from 'firebase/firestore'

describe(' Firestore Rules', () => {
    let testEnv: firebase.RulesTestEnvironment;

    beforeAll(async () => {
        testEnv = await firebase.initializeTestEnvironment({
            firestore: { rules: readFileSync('../firestore.rules', 'utf8') },
            projectId: 'podsuite',
            hub: { host: 'localhost', port: 4000 },
        });
    });

    afterAll(async () => {
        await testEnv.cleanup();
    });

    beforeEach(async () => {
        await testEnv.clearFirestore();
    });


    test('noone should have access to user document', async function () {
        // Setup: Create documents in DB for testing (bypassing Security Rules).
        await testEnv.withSecurityRulesDisabled(async (context) => {
            const testdoc = context.firestore().collection('users').doc('user1234');
            await setDoc(testdoc, { test: 'test1' });
        });

        const unauthedDb = testEnv.unauthenticatedContext().firestore();

        // Then test security rules by trying to read it using the client SDK.
        const testdoc = unauthedDb.collection('users').doc('user1234');

        await firebase.assertFails(getDoc(testdoc));

    });
});

My emulator runs on http://localhost:4000/
These are my rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
       allow read, write: if false;
    }

    match /users/{userId}/salesItems/{documentId} {
      allow read: if true;
      allow write: if false;
    }

    match /users/{userId}/overviews/{documentId} {
      allow read: if true;
      allow write: if false;
    }
  }
}

When I run npm test I am getting an error :

 FAIL  src/tests/rules.test.ts
  ●  Firestore Rules › noone should have access to user document

    FetchError: invalid json response body at http://localhost:4000/emulators reason: Unexpected token < in JSON at position 0

      at node_modules/@firebase/rules-unit-testing/node_modules/node-fetch/lib/index.js:272:32

What is wrong?

Unit tests expect only default ports, seem to ignore firebase.json file

I was following the Unit testing security rules with the Firebase Emulator Suite

There is a section where Todd creates separate functions to initialize the TestApp and AdminApp

function getFirestor(auth) {
     return firebase.initializetestApp({projectId: MY_PROJECT_ID, auth: auth}).firestore
}

However, I would end up with the following error:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

Eventually, I was able to determine that despite the emulator running, it wasn't connecting.
I changed from

const firebase = require('@firebase/testing')

to

const firebase = require('@firebase/rules-unit-testing');

After which I was able to modify the function to work:

const EMULATOR_PORT = 8086

function getFirestore(auth) {
  const db = firebase.initializeTestApp({projectId: MY_PROJECT_ID, auth: myAuth }).firestore();
  db.useEmulator("localhost", EMULATOR_PORT)
  return db
}

This worked for the test app, but when I tried the same for the admin app, it does not work

function getAdminFirestore() {
  const db = firebase.initializeAdminApp({projectId: MY_PROJECT_ID }).firestore();
  db.useEmulator("localhost", EMULATOR_PORT)
  return db
}

ERROR: TypeError: db.useEmulator is not a function

If I comment out the db.usEmulator line I get the

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

I had a firebase.json and .firebaserc in the folder above, I even tried to create another copy in the same folder as the test script, but it also didn't seem to work.

Is there any sample code for v2?

I see the @firebase/rules-unit-testing v2 has just been released. I think no docs has been made available yet? I didn't find any.

Anyway, some example code would be really appreciated, which might take less effort to create than the new docs.

Can't run unit testing due to short mocha timeout

Problem

Been trying to get unit-testing running for hours now. Still can't figure it out.

Steps

First followed the video here: https://www.youtube.com/watch?v=VDulvfBpzZE by Todd Kerpelman and Rachel Myers. Got some errors from that
FirebaseError: No matching allow statements

Then found this repo and downloaded the quick start to run. I followed the README exactly to run
firebase emulators:exec --only firestore "npm run test-firestore"

and now I got

$ firebase emulators:exec --only firestore "npm run test-firestore"
i  emulators: Starting emulators: firestore
i  firestore: Firestore Emulator logging to firestore-debug.log
i  Running script: npm run test-firestore

> [email protected] test-firestore /Users/-/Downloads/quickstart-testing-master/unit-test-security-rules
> mocha --exit test/firestore.spec.js



  1) "before all" hook in "{root}"
View firestore rule coverage information at firestore-coverage.html


  0 passing (3s)
  1 failing

  1) "before all" hook in "{root}":
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
      at listOnTimeout (internal/timers.js:554:17)
      at processTimers (internal/timers.js:497:7)



npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test-firestore: `mocha --exit test/firestore.spec.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test-firestore script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/-/.npm/_logs/2020-10-15T21_07_25_807Z-debug.log
⚠  Script exited unsuccessfully (code 1)
i  emulators: Shutting down emulators.
i  firestore: Stopping Firestore Emulator
i  hub: Stopping emulator hub

Error: Script "npm run test-firestore" exited with code 1

A little help please?

How is this test passing? It's ignoring the collection filter

Nothing is changed in the code below, all taken from the repo as-is:

This is one of the tests that is defined:

  it("tests a Cloud Firestore function", async () => {
    const wrapped = test.wrap(myFunctions.firestoreUppercase);

    // Make a fake document snapshot to pass to the function
    const after = test.firestore.makeDocumentSnapshot(
      {
        text: "hello world",
      },
      "/collection/foo"
    );

    // Call the function
    await wrapped(after);

    // Check the data in the Firestore emulator
    const snap = await admin.firestore().doc("/uppercase/foo").get();
    expect(snap.data()).to.eql({
      text: "HELLO WORLD",
    });
  }).timeout(5000);

And this is the corresponding cloud function

/**
 * Firestore-triggered function which uppercases a string field of a document.
 */
exports.firestoreUppercase = functions.firestore
  .document("/lowercase/{doc}")
  .onCreate(async (doc, ctx) => {
    const docId = doc.id;

    const docData = doc.data();
    const lowercase = docData.text;

    const firestore = admin.firestore();
    await firestore.collection("uppercase").doc(docId).set({
      text: lowercase.toUpperCase(),
    });
  });

Now, this functions works exactly how it's supposed to, when testing manually in the emulator.

  • If I create a document under /lowercase collection, it make an uppercase one.
  • If I create a document under /foobar collection, it doesn't do anything.

That's expected, since the listener of the cloud function is

functions.firestore.document("/lowercase/{doc}")

So it only listens to the /lowercase collection.

However... I don't get how the test is passing.
The test adds a document under the collection /collection

// Make a fake document snapshot to pass to the function
    const after = test.firestore.makeDocumentSnapshot(
      {
        text: "hello world",
      },
      "/collection/foo"
    );

Since the cloud function only listens to /lowercase, how is this passing?

And it doesn't matter what I pass in here as a collection in the test, it always passes. How?

example code passes incorrectly

The function, expectPermissionGetSucceeds, can pass when it shouldn't.

export async function expectPermissionGetSucceeds(promise: Promise<any>) {

If your READ permissions return a PERMISSION_DENIED, then the getDoc promise will return the error code. however since this only expects that promise.not.toBeUndefined, then the error code meets that criteria.

I fixed locally by just adding the second check to make sure that the error code != PERMISSION_DENIED

export async function expectPermissionGetSucceeds(promise: Promise<any>) {
  const successResult = await assertSucceeds(promise);
  expect(successResult).not.toBeUndefined();
  expect(successResult.code).not.toBe('permission-denied' || 'PERMISSION_DENIED');
}

[Question] How to setup a user that has their email verified

Since a helper function for firestore.rules would look like

function emailVerified() {
  return request.auth.token.email_verified;
}

I assumed the setup with this quickstart would look like this

const bob = getAuthedFirestore({
  uid: "bob",
  token: { email_verified: true },
});

Any guidance would help very much.

Problem testing with `firebase.firestore.FieldValue.serverTimestamp()`

I migrated over from @firebase/testing to @firebase/rules-unit-testing and now all of my tests that use firebase.firestore.FieldValue.serverTimestamp() are failing.

Articles collection
       Should allow an admin to update an article:
     Error: Value for argument "data" is not a valid Firestore document. Detected an object of type "FieldValue" that doesn't match the expected instance (found in field "created_at"). Please ensure that the Firestore types you are using are from the same NPM package.)
      at validateUserInput (node_modules/@google-cloud/firestore/build/src/serializer.js:332:15)
      at Object.validateUserInput (node_modules/@google-cloud/firestore/build/src/serializer.js:269:13)
      at validateDocumentData (node_modules/@google-cloud/firestore/build/src/write-batch.js:588:18)
      at WriteBatch.set (node_modules/@google-cloud/firestore/build/src/write-batch.js:247:9)
      at Transaction.set (node_modules/@google-cloud/firestore/build/src/transaction.js:178:26)
      at /Users/victoruvarov/work/tive/tive-backend/test/articles_collection.spec.js:216:19
      at Transaction.runTransaction (node_modules/@google-cloud/firestore/build/src/transaction.js:333:33)
      at async Context.<anonymous> (test/articles_collection.spec.js:215:5)

imports

const firebase = require("@firebase/rules-unit-testing");
const fs = require("fs");
const http = require("http");

dependencies

"devDependencies": {
    "@firebase/rules-unit-testing": "^1.3.13",
    "firebase-admin": "^9.11.0",
    "firebase-tools": "^9.16.0",
    "mocha": "^8.4.0"
  }

Emulator Suite in Google Cloud Shell - TypeError: firebase.initializeTestApp not a function

Environment info

firebase-tools:

Platform: Windows 11 / Google Cloud Shell - Emulator Suite, CS Walkthrough

Test case

Trying to just follow the quickstart testing through Cloud Shell for rules. Getting to step 4 of 11 and it gives the error in the subject line.

"TypeError: firebase.initializeTestApp not a function"

I've looked through the node_modules folder for all the test modules and, no it isn't in the module that the script is looking through. I did see that sometime recently, in a closed issue, initializeTestApp was moved to a different module than it was in before. Perhaps this is the issue.

Steps to reproduce

Just follow the Cloud Shell tutorial explicitly

Expected behavior

The Mocha test starts and runs. Test App is initialized. The CS Walkthrough works out of the box.

Actual behavior

jollyren@cloudshell:~/rules-tutorial/quickstart-testing/cs-walkthrough/functions$ npm run test

> test
> mocha --timeout 5000 --exit

/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/node_modules/yargs/yargs.js:1163
      else throw err
           ^

TypeError: firebase.initializeTestApp is not a function
    at Suite.<anonymous> (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/test.js:53:23)
    at Object.create (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/interfaces/common.js:140:19)
    at context.describe.context.context (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/interfaces/bdd.js:42:27)
    at Object.<anonymous> (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/test.js:51:1)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Module.require (node:internal/modules/cjs/loader:1013:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at /home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/mocha.js:334:36
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/mocha.js:331:14)
    at Mocha.run (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/mocha.js:811:10)
    at Object.exports.singleRun (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/cli/run-helpers.js:108:16)
    at exports.runMocha (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/cli/run-helpers.js:142:13)
    at Object.exports.handler (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/cli/run.js:292:3)
    at Object.runCommand (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/node_modules/yargs/lib/command.js:242:26)
    at Object.parseArgs [as _parseArgs] (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/node_modules/yargs/yargs.js:1104:24)
    at Object.parse (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/node_modules/yargs/yargs.js:566:25)
    at Object.exports.main (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/lib/cli/cli.js:68:6)
    at Object.<anonymous> (/home/jollyren/rules-tutorial/quickstart-testing/cs-walkthrough/functions/node_modules/mocha/bin/mocha:164:29)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47

Shell Cloud for testing Firebase Security Rules Instructions lead to: Error: Cannot find module 'firebase/compat/database'

I started by having problems with my firebase security rules, I tested them in the security rules playground, but since my rules depend on the resource.data.userId, they failed with a null when I tried to test the update instruction. I couldn't find any way to set a resource baseline in the playground. So I decided to give a try a second time to the: https://ssh.cloud.google.com/cloudshell/editor?environment_deployment=firebase&walkthrough_id=firebase_emulator_rules_quickstart
I followed the instructions to the detail, three times, first a few months ago and gave up due to the time is was taking to try to figure this out. Today, I tried again two times, the last time after rebaselining my ssh.cloud.google shell.
It starts with some warnings about requiring node 10 but loading node 12. I am not choosing node version but executing their scripts on the instructions.
The details of what it is showing me is in the attached log files.

Please help!

firebase-debug.log
firestore-debug.log
ui-debug.log

Such examples for Flutter Testing

Hi team,

Is there any such examples for Flutter Testing?
Is would really help to understand how to do similar test within flutter test.

Example of how to test auth triggers

Hi, now that we have the auth emulator, it would be nice to have an example test that showcases how to work with the auth emulator on the test suit.
I've been trying to get this to work, without success.

const firebase = require('@firebase/testing');

// Project id passed by emulators:exec.
const PROJECT_ID = process.env.GCLOUD_PROJECT;
const CREDS = { uid: TEST_USER_ID };

// To get a logged in user pass the CREDS object as param, or null for unauthenticated requests.
const getDB = (creds) => firebase.initializeTestApp({ projectId: PROJECT_ID, auth: creds }).firestore();

// Admin tool to bypass rules and generate data in the db.
const admin = firebase.initializeAdminApp({ projectId: PROJECT_ID });
const getAdminDB = () => admin.firestore();
const getAuth = () => admin.auth();

describe("The cloud functions backend", () => {

    describe("when a user is created", () => {

        it("populates some fields for that user document", async () => {
            const admin = getAdminDB();
            const auth = getAuth();
            const phone = "+11234567891";
            const photo = "https://foo.bar";

            const user = await auth.createUser({ phoneNumber: phone, photoURL: photo, uid: "123" });
            const userRef = admin.collection("users").doc("123");

            await new Promise((resolve) => {
                unsubscribe = userRef.onSnapshot(snap => {
                    const { phoneNumber, photoURL } = snap.data();
                    expect(phoneNumber).to.eq(phone);
                    expect(photoURL).to.eq(photo);
                    unsubscribe();
                    resolve();
                });
            });
        });

    });

});

The error is:

Your API key is invalid, please check you have copied it correctly.

Could it be that the FIREBASE_AUTH_EMULATOR_HOST is not being set by firebase emulators:exec? and need to be specified explicitly? Like: auth().useEmulator("localhost:9099")?

Appreciate some ideas on how to troubleshoot or some code snippets that use the auth emulator in tests. Thanks!

Request.auth != null always returns false when unit testing Firestore security rules using authenticatedContext

This is the test code that fails

const alice = await testEnv.authenticatedContext('alice');
await assertFails(await getDoc(doc(await alice.firestore(), '/users/abc_123')));

Here is my security rules

  match /users/{userID} {
    	allow read: if
       	  request.auth != null &&  // This is in line 7
          request.auth.uid == userID && 
          request.auth.uid == resource.data.userID;
      allow delete: if false;
    }

This is the log of the test that fails

Users tests
       should not allow users to read other user's data:
     FirebaseError: 
false for 'get' @ L7

Checking the request data using the firebase emulator suite, the request has an auth value. It is not null. request.auth != null SHOULD return true but it always return false no matter what.

 ➜ firebase --version
10.7.2

any ideas what could be the cause of this issue?

Test a firestore rule like "allow list"

In unit-test-security-rules-v9, show should I test an allow list rule, like in this example of firestore rules:

    match /users/{userId}/{allPaths=**} {
    	allow list: if request.auth.token.isAdmin;
    }

In my use-case, I want to allow users to get their own info but only admins can list everybody.

Thanks

[firestore-emulator/browser-quickstart]: feature request: add example for permissions and authorization for browser

This request is only for the browser-quickstart. For other quickstarts for the emulator, I'd use @firebase/testing, as the following request has been implemented in examples in this repo via initializeTestApp.


I wanted to get some thoughts on how to cleanly handle custom permissions with the firebase emulator clientside. Currently, I am doing something like the following when firebase is being initialized (for dev purposes):

function createUnsecuredJwt(auth: object): string {
  // Unsecured JWTs use "none" as the algorithm.
  const header = {
    alg: "none",
    kid: "fakekid"
  };
  // Ensure that the auth payload has a value for 'iat'.
  (auth as any).iat = (auth as any).iat || 0;
  // Use `uid` field as a backup when `sub` is missing.
  (auth as any).sub = (auth as any).sub || (auth as any).uid;
  if (!(auth as any).sub) {
    throw new Error("auth must be an object with a 'sub' or 'uid' field");
  }
  // Unsecured JWTs use the empty string as a signature.
  const signature = "";
  return [
    util.base64.encodeString(JSON.stringify(header), /*webSafe=*/ false),
    util.base64.encodeString(JSON.stringify(auth), /*webSafe=*/ false),
    signature
  ].join(".");
}

const app = firebase.initializeApp(
  { projectId: "my-app" },
  { name: "my-app" }
);

const _jwt = createUnsecuredJwt({
  uid: "my-custom-id",
  currentGroupId: "my-custom-group-id",
  role: "admin"
});

(app as any).INTERNAL.getToken = () => {
  return Promise.resolve({ accessToken: _jwt });
};

All this functionality is copied directly from @firebase/testing, following these code paths:
https://github.com/firebase/firebase-js-sdk/blob/master/packages/testing/src/api/index.ts#L101
https://github.com/firebase/firebase-js-sdk/blob/master/packages/testing/src/api/index.ts#L66-L87

https://github.com/firebase/firebase-js-sdk/blob/master/packages/testing/src/api/index.ts#L130-L147
Note: the last one is slightly different due to some recent changes published 5 days ago

Questions

  1. Is there a better way to do this? I tried importing @firebase/testing in the browser but everytime I do that I get issues with grpc dependencies.
  2. Does the firestore emulator team plan to support permissions for firestore-emulator/browser-quickstart?

Simple http function throws ensure "done()" is called instead of actual assertion error.

Change the following assertion so that it fails:


It will throw the following error:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. ([redacted]/functions/lib/test/index.test.js)

This makes it very difficult to debug issues. Instead, I recommend (unless there's a better way to debug this):

try {
  expect(text).to.eq("text: input");
} catch (e) {
  console.error(e);
  throw e;
}

Example for asserting `HttpsError` thrown by cloud function

It would be really nice to have an example how to assert HttpsError, which are thrown by a cloud function.

exports.testCallable = functions.https.onCall((data, context) => {
    console.log('testCallable');
    return new functions.https.HttpsError('ok', 'this is an error');
})

How to write a test, that a HttpsError with the message this is an error was thrown?

typescript please!

Desperately needing samples in TypeScript. I'm trying to test functions now and don't have a clue what parameters are possible on Request and Response objects. Have Googled for hours and can't find what I need. Would love to see some really basic function tests in Mocha and Typescript against the emulator. Tests for...

HTTP
If function is supposed to return an uppercase version of what is passed in, check that
Function grabs parameters out of the query string
If function is supposed to return an error code, like forbidden, show that
If function is supposed to write to a document
Fail if not authenticated, return proper status code
Check claims, fail if not met

INTERNAL SERVER
On user create, create a document
On user delete, delete a document
On document changes, do something

===

Digging through your code a bit I see references to "core" and Express. Can I even get these types into my code? I'd like to strongly type my request and response objects. Where do I import these from?

===

Investigated some more and see it is Express web server under the covers? I'm going to assume that testing this in Typescript is going to be tough because there are so many possible properties on the Request object - headers and such - and so many ways to build the response and I'd need test helpers to construct these things in such a way that they'd type check. Also don't know how this interacts with the Auth stuff - do I get the token from the headers or from the Auth API. This is really beyond me - too much to learn - probably will just skip the unit testing. Can't do it without some getting started info from you with common cases in code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.