[英]Log in Firebase auth and get Id token in flutter tests
我想為我在 flutter 中創建的應用程序編寫一些集成測試。
我想檢查前端和后端之間的集成,為此,我需要從 Firebase 生成一個有效的 JWT Id 令牌(來自測試憑據,將作為機密進行管理,但這超出了 scope問題)。
注意:我知道我所有的庫都是最新的(當某些依賴項已過期時,有時會出現相同的錯誤消息),因為當我在模擬器。
我在嘗試運行規范的登錄方式並在測試中獲取 id 令牌時遇到問題。
到目前為止,我已經編寫了如下測試,但是當我嘗試運行它們時它們確實會引發錯誤:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
// + some custom imports for type SingleRecipientMessageHeader, etc...
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('messageRepository', () {
late final String? jwt;
setUp(() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.android,
); // <= this command raises the error!
final instance = firebase_auth.FirebaseAuth.instance;
await instance.signInWithEmailAndPassword(
email: "<REDACTED>", password: "<REDACTED>");
jwt = await instance.currentUser?.getIdToken();
});
tearDown(() {});
test('message repository dummy test', () async {
List<SingleRecipientMessageHeader> messages =
await MessageRepository().fetchMessages(jwt!);
... // the actual integration tests follow...
});
});
}
但是,當我嘗試運行這些測試時,上面標記的命令會引發以下錯誤:
PlatformException(channel-error, Unable to establish connection on channel., null, null)
package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart 203:7 FirebaseCoreHostApi.initializeCore
據我了解,在運行測試時,不存在實際平台,因此出現連接錯誤。
有誰知道我如何在我的測試套件中實現登錄並從 Firebase 獲取 JWT Id 令牌?
非常感謝!
根據Firebase 文檔,我最終通過調用 Firebase API 獲得了 jwt 用於我的測試:
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// + some custom imports for type SingleRecipientMessageHeader, etc...
void main() {
group('messageRepository', () {
late final String? jwt;
setUp(() async {
http.Response response = await http.post(
Uri.parse(
'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=<MY API KEY>'),
headers: <String, String>{},
body: jsonEncode(<String, String>{
'email': '<REDACTED>',
'password': '<REDACTED>',
'returnSecureToken': 'true',
}),
);
jwt = jsonDecode(response.body)['idToken'];
});
tearDown(() {});
test('message repository dummy test', () async {
List<SingleRecipientMessageHeader> messages =
await MessageRepository().fetchMessages(jwt);
expect(messages[0].headerStatus, HeaderStatus.active);
// the actual integration tests follow...
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.