[英]how to test react native code with jest and mock for firebase
我正在尝试使用 jest 测试反应原生方法,我的问题是修改后的值与预期值不同。 因为 function 使用 firebase 我做了模拟所以这是我想使用的方法
insertUserAction= async ()=>{
console.log("inside inserUserAction")
var userActionKey =firebase.database().ref().child('userActions').push().key;
firebase.database().ref('userActions/'+userActionKey).set(
{
userID: firebase.auth().currentUser.uid,
ActionID:'001',
time:new Date().getHours(),
day:moment().format('dddd'),
Repetition:'1',
inRoutine:'0',
insertedDate: new Date().getFullYear()+'/'+new Date().getMonth()+'/'+new Date().getDate(),
})
.then(() => {
console.log("enter then");
this.setState(() =>{
return {
userID:firebase.auth().currentUser.uid,
ActionID:'001',
time:new Date().getHours(),
day:moment().format('dddd'),
Repetition:'1'}
});
console.log('inserted')
}).catch((error)=>{
console.log(error)
});
}
这里是 firebase 配置
const firebaseConfig = {
apiKey: "******",
authDomain: "*****",
databaseURL: "*****",
projectId: "*****",
storageBucket: "*******",
messagingSenderId: "******",
appId: "*****",
};
这里是测试
import React from 'react';
import HomeScreen from '../screens/HomeScreen';
import renderer from 'react-test-renderer';
jest.mock("firebase/app", () => {
const data = { ActionID: "unnamed" };
const snapshot = { val: () => data };
return {
firebaseConfig: jest.fn().mockReturnValue({
database: jest.fn().mockReturnValue({
ref: jest.fn().mockReturnThis(),
once: jest.fn(() => Promise.resolve(snapshot))
})
})
};
});
test('testing Analysis feature ', () => {
const component = renderer.create(<HomeScreen ActionID="5" />);
const instance = component.getInstance();
instance.insertUserAction();
expect(instance.state.ActionID).toBe("001");
});
我不确定模拟
正如你所看到的,没有必要模拟firebaseConfig,因为这只需要连接到真实的数据库,但为了模拟目的它不需要,所以基本上你只需要模拟你真正需要的东西,在这种情况下你需要一些东西像这样:
jest.mock("firebase/app", () => {
const data = { ActionID: "unnamed" };
const snapshot = { val: () => data };
return {
firebaseConfig: jest.fn().mockReturnValue({}),
auth: jest.fn().mockReturnValue({ currentUser: { uid: 'uid' } }),
database: jest.fn().mockReturnValue({
ref: jest.fn().mockImplementation(() => ({
child: jest.fn().mockImplementation(() => ({
push: jest.fn().mockReturnValue({
key: 'someValueAsKey'
})
})),
set: jest.fn(),
})),
once: jest.fn(() => Promise.resolve(snapshot))
})
};
});
我保留了firebaseConfig
模拟,因为我不想删除您的代码,如果您愿意,可以将其删除。
请记住,您可以使用一些 firebase 模拟库,例如这个https://www.npmjs.com/package/firebase-mock
我希望这可以帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.