【问题标题】:How do I write tests for a transformed stream in Flutter?如何在 Flutter 中为转换后的流编写测试?
【发布时间】:2020-01-15 00:09:58
【问题描述】:

我有一个 Provider,它有一个方法可以从 Firebase 获取数据作为流,将其转换为列表并返回 Stream<List<Model>> 。我正在尝试编写一个测试,以检查List 中的项目是否与我期望的相同。我该怎么做?

我当前的代码:

test('getContacts returns a empty list when there is no contact',() async{
      when(sharedPreferencesMock.get(any)).thenReturn('uid'); //mock the sharedprefs
      documentSnapshot = DocumentSnapshotMock();  //mock documentsnapshot
      when(documentSnapshot.exists).thenReturn(true); // this is done to pass the getUidByUsername method
      documentReference = DocumentReferenceMock(documentSnapshotMock: documentSnapshot);
      documentReference.setData({
        'uid':'uid',
        'contacts':[]  // setting the usename in the data already so that duplicate contact exception is thrown
      });
      userDataProvider.getContacts().asBroadcastStream().listen((data){
        expect(data.length,0);
      });

    });

以及提供者方法

  @override
  Stream<List<Contact>> getContacts() {
    CollectionReference userRef = fireStoreDb.collection(Paths.usersPath);
    DocumentReference ref =
        userRef.document(SharedObjects.prefs.get(Constants.sessionUid));


    return ref.snapshots().transform(StreamTransformer<DocumentSnapshot, List<Contact>>.fromHandlers(handleData: (documentSnapshot, sink) async{
      List<String> contacts;
      if (documentSnapshot.data['contacts'] == null) {
        ref.updateData({'contacts': []});
        contacts = List();
      } else {
        contacts = List.from(documentSnapshot.data['contacts']);
      }
      List<Contact> contactList = List();
      for (String username in contacts) {
        print(username);
        String uid = await getUidByUsername(username);
        DocumentSnapshot contactSnapshot = await userRef.document(uid).get();
        contactList.add(Contact.fromFirestore(contactSnapshot));
      }
      sink.add(contactList);
    }));

  }

更新:

 StreamController streamController = StreamController<List<Contact>>();
      StreamSink<List<Contact>> sink = streamController.sink;
      Stream<List<Contact>> stream = streamController.stream;
      stream.listen((List<Contact> list){
        expect(list.length,1);
      });
      userDataProvider.mapDocumentToContact(userCollection, userRef, documentSnapshot, sink);
      streamController.close();

【问题讨论】:

    标签: firebase flutter dart stream


    【解决方案1】:

    将您当前传递给 StreamTansformer 的 lambda 函数设为单独的函数并对其进行测试。 如果你想测试完整的功能,pub 上有一个 Firebase 模拟包。

    【讨论】:

    • 非常感谢!我提取了 lambda 函数并为它编写了测试。现在正在过去。我已经用代码 sn-p 更新了这个问题。你能检查一下这是否是正确的做法吗?
    • 完成。谢谢@Thomas
    猜你喜欢
    • 2022-07-04
    • 2014-07-05
    • 2020-08-22
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多