简体   繁体   中英

Flutter Test Mock GraphQL mutation doesn't find stub

I'm using mockito and graphql packages in my flutter app in order to write tests for my graphql mutations without it actually doing a database read. The way Mockito works is that i set a "when" clause which makes it so whenever that particular method is called on my mocker it uses what I defined instead of what would run normally.

I've defined a when for my mocked GraphQLClient for client.mutate(). however, when I call mutate it says that there is no mock defined. I've done research online and several people fixed the issue by making sure they define the when first, which I have done, but it still hasn't solved my issue. Here is my initialization and packages

import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';

import 'package:graphql/client.dart' as graphql;
import 'login_screen_test.mocks.dart';

@GenerateMocks([graphql.GraphQLClient])

and the client and mutation

  final mockClient = MockGraphQLClient();
  MutationOptions loginMutation = MutationOptions(
    document: gql(
      r'''
        mutation Login($email: String!, $password: String!) {
          login(input: {email:$email password:$password}) {
            accessToken
            refreshToken
            user {
              id
            }
          }
        }
      ''',
    ),
    variables: <String, dynamic>{
      'email': 'doodle@noodle.com',
      'password': 'password',
    },
  );

and now the test case

  test('Login success if done correctly', () async {
    when(mockClient.mutate(loginMutation)).thenAnswer((_) async => graphql.QueryResult(source: null, data: {'login': {'accessToken': 'ooglyboogly', 'refreshToken': 'mtnDew'}}));
    await userRepo.loginEmailPassword(mockClient, email: 'doodle@noodle.com', password: 'password');
    expect(store.state.auth.accessToken, isNot(''));
  });

Make sure the mocks file is generated. The file name should be something like that: 'your_test_file_name.mocks.dart'

if you can't find the generated mocks file try running

flutter pub run build_runner build

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM