在我的node js项目中,我有一个firebase.js文件,该文件连接到实时数据库并导出一些与用户数据有关的功能。
firebase.js
'use strict'
const firebase = require('firebase')
const config = {
apiKey: 'xxx',
authDomain: 'xxx',
databaseURL: 'xxx',
projectId: 'xxx',
storageBucket: 'xxx',
messagingSenderId: 'xxx'
}
firebase.initializeApp(config)
const db = firebase.database()
module.exports.getUserByUid = async user => {
const usersRef = db.ref(`users/${user.uid}`)
const snapshot = await usersRef.once('value')
let userToReturn
if(snapshot.exists()) {
userToReturn = snapshot.val()
userToReturn.uid = snapshot.key
} else {
throw Error('user not found')
}
return userToReturn
}
我从userProcessor.js文件中调用它
userProcessor.js
const db = require('../database/firebase')
module.exports.getUserByUid = async request => {
const user = await this.extractUserData(request)
const userToReturn = await db.getUserByUid(user) //here
return userToReturn
}
..
module.exports.extractUserData = request => ({
uid: request.body.uid,
username: request.body.username,
email: request.body.email})
如果我直接从文件中调用它,它将起作用。
我正在使用koa
将其公开给网络api上的GET
请求,并且工作正常(已通过Postman测试)。
但是当我尝试对其进行小丑测试时,它会抛出:
TypeError: firebase.initializeApp is not a function
15 | }
16 |
> 17 | firebase.initializeApp(config)
| ^
userProcessor.test.js
const userProcessor = require('../modules/processors/userProcessor')
test('retrieve user that does not exist', async done => {
try {
await userProcessor.getUserByUid({body: {uid: '99xa999axa9x9x'}})
} catch(err) {
expect(err.message).toBe('user not found')
done()
}
})
package.json
"devDependencies": {
"eslint": "^5.9.0",
"eslint-config-google": "^0.11.0",
"firebase": "^5.5.8",
"jest": "^23.6.0"
},
"dependencies": {
"firebase-admin": "^6.1.0",
"http-status-codes": "^1.3.0",
"koa": "^2.6.2",
"koa-bodyparser": "^4.2.1",
"koa-cors": "0.0.16",
"koa-router": "^7.4.0",
"supertest": "^3.3.0"
}
答案 0 :(得分:0)
问题是我在与__mocks__
的文件夹中有一个名为firebase.js
的文件夹,其中包含另一个名为firebase.js
的文件。
解决方案正在改变
const firebase = require('firebase')
到
const firebase = require('../../node_modules/firebase')