Trying to test my cubit but i keep getting this error
MissingStubError: 'fetchOrganisationCountWithFilter'
No stub was found which matches the arguments of this method call:
fetchOrganisationCountWithFilter(QueryFilterOr(null, null, null, null, [QueryFilterElement(name, FilterOperation.matchPhrase, Mock Organisation, null, null), QueryFilterElement(domain, FilterOperation.eq, mock.com, null, null)]))
Here is the bloc test
void blocTestFetchOrganisationCount() {
blocTest<OrganisationFormCubit, OrganisationFormState>(
'Given a valid organisation, '
'when fetching organisation count, '
'then return 0',
build: () => _organisationFormCubit,
act: (cubit) async {
when(_organisationRepo.fetchOrganisationCountWithFilter(
QueryFilterOr(
[
QueryFilterElement(
'name',
FilterOperation.matchPhrase,
mockOrganisation.name,
),
if (mockOrganisation.domain != null)
QueryFilterElement(
'domain',
FilterOperation.eq,
mockOrganisation.domain,
),
],
),
)).thenAnswer((_) => Future(() => Success(0)));
await cubit.fetchOrganisationCount(mockOrganisation);
},
expect: _expectProcessingStateEmitted,
);
}
And here is the method that's not matching
#override
Future<Result<int>> fetchOrganisationCountWithFilter(
QueryFilter filter,
) async {
final response = await _organisationApi.countWithFilter(filter);
if (response.hasError) {
final error = response.error;
return Failed(Exception('${error.code!} ${error.message!}'));
}
return Success<int>(response.item);
}
Not sure how to fix it or make it work, spent way too long trying to figure out what's wrong but couldn't , any help is appreciated!
Related
Inside my Algolia application I have to indices which both contain users. Both of them must have a uid and a username (along other fields). I managed to implement the search for on of the indices. But how can I search in both indices?
I followed this tutorial but it does not say anything about searching multiple indices.
I found this about searching multiple indices but how can I do that in Flutter in combination with `Hits Searcher and infinite_scrolling_pagination.
This is my setup:
Stream<SearchMetadata> get _searchUsersMetadata =>
_userSearcher.responses.map(
SearchMetadata.fromResponse,
);
final PagingController<int, AlgoliaUser> _pagingController =
PagingController(firstPageKey: 0);
#override
void initState() {
super.initState();
_searchPage.listen((page) {
if (page.pageKey == 0) {
_pagingController.refresh();
}
_pagingController.appendPage(page.items, page.nextPageKey);
}).onError((error) => _pagingController.error = error);
_pagingController.addPageRequestListener(
(pageKey) => _userSearcher.applyState(
(state) => state.copyWith(page: pageKey),
),
);
}
final _userSearcher = HitsSearcher(
applicationID: 'myAppID',
apiKey: 'myApiKey',
indexName: 'users',
);
Stream<HitsPage> get _searchPage => _userSearcher.responses.map(
HitsPage.fromResponse,
);
_onSearchChanged(String query) {
if (_debounce?.isActive ?? false) {
_debounce?.cancel();
}
_debounce = Timer(const Duration(milliseconds: 500), () {
_userSearcher.applyState(
(state) => state.copyWith(
query: _searchTextEditingController.text,
page: 0,
),
);
});
}
If secure storage have user_id, I want auth state to change true
Error: A non-null value must be returned since the return type 'bool'
doesn't allow null.
check: (context, location) {
final _routerDelegate = BeamerDelegate(
updateListenable: authNotifier,
guards: [
BeamGuard(
beamToNamed: (origin, target) => '/$locationAuth',
pathPatterns: [
...HomeLocation().pathPatterns,
],
check: (context, location) {
final loginNotifier =
Provider.of<AuthenticationNotifier>(context, listen: false);
Future<bool> _getUserId() async {
const storage = FlutterSecureStorage();
final userId = await storage.read(key: "userId");
if (userId != null) {
loginNotifier.setUserAuth(true);
}
return loginNotifier.isAuthenticated;
}
_getUserId().then((val) => val);
},
),
],
locationBuilder: BeamerLocationBuilder(beamLocations: [
HomeLocation(),
AuthLocation(),
]),
);
Write all that in asynchronous mode.
remove all async & await
I am having a currency picker, which onSelect I want to fetch some records based on the selected currency and display the data in a text widget.
So my endpoint url will be like this wwww.fetchrecordbasedoncurrency?curr=${selectedCurrency}
This is the currency picker
ElevatedButton(
onPressed: () {
Navigator.pop(context);
showCurrencyPicker(
context: context,
showFlag: true,
showSearchField: true,
showCurrencyName: true,
showCurrencyCode: true,
onSelect: (Currency currency) {
setState(() {
fetchData();
});
fetchData();
},
currencyFilter: <String>[
'AUD',
'CAD',
'EUR',
'USD'
],
favorite: ['USD'],
);
},
child: const Text('Select Payment Currency'),
),
This is the method responsible for fetching the data
void fetchData() async {
try {
setState(() {
isLoading = true;
});
var response = await networkHandler.get(
networkHandler.url + 'fetch-data.php?curr=${currencyType}');
getBankInfo = BankInfo.fromJson(response);
print("Bank Currency: ${getBankInfo.bank!.currency}");
} catch (ex) {
print({ex, 'An error occured while fetching bank data'});
} finally {
setState(() {
isLoading = false;
});
}
}
It fetches the data successfully, but I get this error Null check operator used on a null value
on the widget below which is trying to display a record based on the selected currency
Text('${getBankInfo.bank!.name}')
Hey you are getting this error in ${getBankInfo.bank!.name}. This error is because you are getting getBankInfo.bank is null and by using ! you are making it non-nullable. If you want to avoid this error then you can use ? instead of !, but by using ? if getBankInfo.bank is null then you will see null on screen. You can use null aware operator also like this getBankInfo.bank?.name ?? "".
You need to debug this line also getBankInfo = BankInfo.fromJson(response); to confirm you are getting right data or not to parse json
I'm getting the below error while I'm trying to implement bloc testing in my flutter project
type 'Null' is not a subtype of type 'Future<bool>'
package:mynovatium/features/signup/repositories/signup_repository.dart 10:16 MockRepository.createAccountsignup
Following are the corresponding files that might help identify the cause of the error
signup_bloc_test.dart
class MockRepository extends Mock implements SignUpRepository {}
void main() async {
await configureInjection(inj.Environment.test);
group('SignupBloc', () {
late SignUpBloc signUpBloc;
late SignUpRepository signupRepositoryMock;
setUp(() {
signupRepositoryMock = MockRepository();
signUpBloc = SignUpBloc(signUpRepository: signupRepositoryMock);
});
test('initial state of the bloc is [AuthenticationInitial]', () {
expect(SignUpBloc(signUpRepository: signupRepositoryMock).state,
SignupInitial(),);
});
group('SignUpCreateAccount', () {
blocTest<SignUpBloc, SignUpState>(
'emits [SignUpCreateAccountLoading, SignupInitial] '
'state when successfully Signed up',
setUp: () {
when(signupRepositoryMock.createAccount(
'Nevil',
'abcd',
'nikunj#gmail.com',
'english',
),).thenAnswer((_) async => Future<bool>.value(true));
},
build: () => SignUpBloc(signUpRepository: signupRepositoryMock),
act: (SignUpBloc bloc) => bloc.add(
const SignUpCreateAccount(
'Nevil',
'abcd',
'nikunj#gmail.com',
'english',
),
),
expect: () => [
SignUpCreateAccountLoading(),
SignupInitial(),
],
);
});
});
}
signup_repository.dart
This is the code for the signup repository.
class SignUpRepository {
Future<bool> createAccount(String _firstName, String _lastName, String _eMailAddress, String _language) async {
final Response _response;
try {
_response = await CEApiRequest().post(
Endpoints.createCustomerAPI,
jsonData: <String, dynamic>{
'firstName': _firstName,
'lastName': _lastName,
'email': _eMailAddress,
'language': _language,
'responseUrl': Endpoints.flutterAddress,
},
);
final Map<String, dynamic> _customerMap = jsonDecode(_response.body);
final CustomerModel _clients = CustomerModel.fromJson(_customerMap['data']);
if (_clients.id != null) {
return true;
} else {
return false;
}
} on KBMException catch (e) {
final KBMException _exception = e;
throw _exception;
}
}
}
If anyone has any ideas on what might be the issue here, please help!!
Okay so in the above code you need to stub the methods within the mock repository as well and override it to have it return something incase null is being returned.
class MockRepository extends Mock implements SignUpRepository {
#override
Future<bool> createAccount(String? _firstName, String? _lastName, String? _eMailAddress, String? _language) =>
super.noSuchMethod(Invocation.method(#createAccount, [_firstName, _lastName, _eMailAddress, _language]),
returnValue: Future<bool>.value(false),);
}
Doing something like that done in the above code works well.
I want to test my GraphQL Query. I have my GraphQL client, and I use a remote datasource to do my requests.
class MockGraphQLClient extends Mock implements GraphQLClient {}
void main() {
RemoteDataSource RemoteDataSource;
MockGraphQLClient mockClient;
setUp(() {
mockClient = MockGraphQLClient();
RemoteDataSource = RemoteDataSource(client: mockClient);
});
group('RemoteDataSource', () {
group('getDetails', () {
test(
'should preform a query with get details with id variable',
() async {
final id = "id";
when(
mockClient.query(
QueryOptions(
documentNode: gql(Queries.getDetailsQuery),
variables: {
'id': id,
},
),
),
).thenAnswer((_) async => QueryResult(
data: json.decode(fixture('details.json'))['data'])));
await RemoteDataSource.getDetailsQuery(id);
verify(mockClient.query(
QueryOptions(
documentNode: gql(Queries.getDetailsQuery),
variables: {
'id': id,
},
),
));
});
});
});
}
I would like to know how to mock the response of my query. Currently it does not return a result, it returns null
But I don't understand why my query returns null, although I have mocked my client, and in my "when" method I use a "thenAnwser" to return the desired value
final GraphQLClient client;
ChatroomRemoteDataSource({this.client});
#override
Future<Model> getDetails(String id) async {
try {
final result = await client.query(QueryOptions(
documentNode: gql(Queries.getDetailsQuery),
variables: {
'id': id,
},
)); // return => null ????
if (result.data == null) {
return [];
}
return result.data['details']
} on Exception catch (exception) {
throw ServerException();
}
}
The argument on which when should mock an answer for is quite complex. You might be easier to just use any in your test case.
when(mockClient.query(any)).thenAnswer((_) async => QueryResult(
data: json.decode(fixture('details.json'))['data'])));
any is provided by Mockito to match any argument.
In the
graphql_flutter: ^5.0.0
you need the add source as null or QueryResultSource.network, when call method when can you pass any so you don't need to pass QueryOptions( documentNode: gql(Queries.getDetailsQuery), variables: { 'id': id, }, ),
here is final code:
when(mockClient.query(any)).thenAnswer((_) async => QueryResult( data: json.decode(fixture('details.json'))['data'], ,source: null)));
any is not accepted with graphQLClient.query(any)) as it accepts non nullable QueryOptions<dynamic>
Using mockito: ^5.1.0 , you will get the warning: The argument type 'Null' can't be assigned to the parameter type 'QueryOptions<dynamic>'
I solved it by creating the mocked QueryOptions as:
class SutQueryOption extends Mock implements QueryOptions {}
void main() {
SutQueryOption _mockedQueryOption;
....
setUp(() {
SutQueryOption _mockedQueryOption = MockedQueryOptions();
....
});
when(mockClient.query(_mockedQueryOption)).thenAnswer((_) async => ....