简体   繁体   中英

mock transaction in runTransaction

i want to mock code inside a runTransaction function.

example code:

await admin.firestore().runTransaction(async transaction => {
  const hubDocument = admin.firestore().collection("Acme").doc('4');
  const hubData = (await transaction.get(hubDocument)).data();
  newData = {
    ...hubData,
    someAttribute: 'some new value'
  };
  transaction.update(hubDocument, newData);
})

i want to mock transaction , check if it is called with the right data etc.pp.

I managed to mock firestore() but do not know how to mock the transaction parameter.

I have not tested this, but I asume something like this should do the trick:

import { Transaction } from '@google-cloud/firestore';

const origTransactionGet = Transaction.prototype.get
Transaction.prototype.get = function () {
   console.log(arguments, "< Intercepted Transaction.prototype.get")
   return origTransactionGet.apply(this, arguments)
}

// your code
await admin.firestore().runTransaction(async transaction => {
  const hubDocument = admin.firestore().collection("Acme").doc('4');
  const hubData = (await transaction.get(hubDocument)).data();
  newData = {
    ...hubData,
    someAttribute: 'some new value'
  };
  transaction.update(hubDocument, newData);
})

As @FiodorovAndrei commented, the alternative, perhaps more comfortable if you use jest would be to just use firestore-jest-mock to mock the Firestore functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM