伙计,这个 firebase 单元测试真的让我很兴奋。
我已经阅读了文档并阅读了他们提供的示例,并对我的一些更基本的 Firebase 功能进行了单元测试,但我一直遇到一些问题,我不确定如何验证该transactionUpdated
功能是否传递给refs.transaction
正确地更新了current
对象。
我的挣扎可能最好用他们的child-count
示例代码和我为它编写单元测试的糟糕尝试来说明。
假设我要进行单元测试的函数执行以下操作(直接取自上面的链接):
// count.js
exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(event => {
const collectionRef = event.data.ref.parent;
const countRef = collectionRef.parent.child('likes_count');
// ANNOTATION: I want to verify the `current` value is incremented
return countRef.transaction(current => {
if (event.data.exists() && !event.data.previous.exists()) {
return (current || 0) + 1;
}
else if (!event.data.exists() && event.data.previous.exists()) {
return (current || 0) - 1;
}
}).then(() => {
console.log('Counter updated.');
});
});
单元测试代码:
const chai = require('chai');
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
const assert = chai.assert;
const sinon = require('sinon');
describe('Cloud Functions', () => {
let myFunctions, functions;
before(() => {
functions = require('firebase-functions');
myFunctions = require('../count.js');
});
describe('countlikechange', () => {
it('should increase /posts/{postid}/likes/likes_count', () => {
const event = {
// DeltaSnapshot(app: firebase.app.App, adminApp: firebase.app.App, data: any, delta: any, path?: string);
data: new functions.database.DeltaSnapshot(null, null, null, true)
}
const startingValue = 11
const expectedValue = 12
// Below code is misunderstood piece. How do I pass along `startingValue` to the callback param of transaction
// in the `countlikechange` function, and spy on the return value to assert that it is equal to `expectedValue`?
// `yield` is almost definitely not the right thing to do, but I'm not quite sure where to go.
// How can I go about "spying" on the result of a stub,
// since the stub replaces the original function?
// I suspect that `sinon.spy()` has something to do with the answer, but when I try to pass along `sinon.spy()` as the yields arg, i get errors and the `spy.firstCall` is always null.
const transactionStub = sinon.stub().yields(startingValue).returns(Promise.resolve(true))
const childStub = sinon.stub().withArgs('likes_count').returns({
transaction: transactionStub
})
const refStub = sinon.stub().returns({ parent: { child: childStub }})
Object.defineProperty(event.data, 'ref', { get: refStub })
assert.eventually.equals(myFunctions.countlikechange(event), true)
})
})
})
我用我的问题注释了上面的源代码,但我会在这里重申。
我如何验证传递给事务存根的transactionUpdate
回调startingValue
是否会接受我的并将其变异为expectedValue
然后允许我观察该更改并断言它发生了。
这可能是一个非常简单的问题,有一个明显的解决方案,但我对测试 JS 代码非常陌生,因为所有东西都必须被存根,所以它有点学习曲线......感谢任何帮助。