# firebaseのunit test ###### tags: `個人用` ## 必要なパッケージ - firebase-functions-test - documentSnapshotをmockしてくれる - firebase-functions - firebase-functions-testを動かすのに必要 - firebase-admin - firebase-functions-testを動かすのに必要 - sinon - 関数のモック作成 ## サンプルコード ```javascript= // assets/js/firebase import firebase from 'firebase' export default class Firebase { constructor (config) { if (!firebase.apps.length) { firebase.initializeApp(config) } } async getData (id) { const res = await firebase.firestore().collection('test').doc(id).get() return res.data().name } } ``` ```javascript= // テストコード import firebase from 'firebase' // firebase configを初期化 const test = require('firebase-functions-test')() import sinon from 'sinon' import Firebase from '@/assets/js/firebase' // firestoreをmock const firestoreStub = sinon.stub() sinon.stub(firebase, 'firestore').get(() => firestoreStub) const testFirebase = new Firebase() describe('firebase', () => { it('getData', async () => { const collection = 'test' const document = 'documentId' // documentSnapshotをmock const snap = test.firestore.makeDocumentSnapshot({ name: 'sample' }, '/test/sample') const refStub = sinon.stub() const docStub = sinon.stub() const getStub = sinon.stub() // collectionを作成 firestoreStub.returns({ collection: refStub }) // documentを作成 refStub.withArgs(collection).returns({ doc: docStub }) // getの関数を作成 docStub.withArgs(document).returns({ get: getStub }) // getが叩かれた時のレスポンスを作成 getStub.returns(snap) const res = await testFirebase.getData(document) expect(res).toEqual('sample') }) }) ``` ## コメント - firebaseクラス自体は```__mock__```を使用する - おそらくprinterクラスも```__mock__```で作成した方がいい気がする - firebaseの関数のテストは使用するcollectionとdocumentを全てstubしなければならないのでめちゃくちゃめんどくさそう - self-orderの時はこれが理由でfirebaseのテストしなかった? - snapshotのテストはまだできてないです - snapshotで使用しているcollectionとdocumentをstubすれば可能なきがしてる
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up