Why does my mockito failed test when actual result same as the expected result? flutter - flutter

I'm using Mockito in flutter application and want to add some test cases:
this run failed while the actual result is the same as expected result, here's my test file:
#GenerateMocks([ResumeParserDataSource])
void main() {
late MockResumeParserDataSource resumeParserDataSource;
late ResumeParserController resumeParserController;
late ResumeParserRepo resumeParserRepo;
setUp(() async {
Get.reset();
resumeParserDataSource = MockResumeParserDataSource();
resumeParserRepo =
Get.put(ResumeParserRepo(dataSource: resumeParserDataSource));
resumeParserController = Get.put(ResumeParserController());
});
group('Upload resume that uploaded into API:\n', () {
test(
'~succeed state~ api get response and parsed it into model JSON "ParsedDetailsResume"',
() async {
when(resumeParserRepo
.getResumeDetailsAfterParsing(ResumeParserTestUtil.fileName))
.thenAnswer((_) async => Right(
ResumeParserTestUtil.parsedResumeDetailsFunction(
ResumeParserTestUtil.parsedResumeDetailsModel1)));
await resumeParserController
.parseResumeToAPI(ResumeParserTestUtil.fileName);
await waitForAPIResponse();
expect(
resumeParserController.parsedResume.value,
some(ResumeParserTestUtil.parsedResumeDetailsFunction(
ResumeParserTestUtil.parsedResumeDetailsModel1)));
expect(resumeParserController.error.value, none());
});
});
}
here's my ResumeParserController:
class ResumeParserController extends GetxController {
static ResumeParserController get to => Get.find();
final resumeParserRepo = ResumeParserRepo.to;
Rx<Option<ParsedResumeDetails>> parsedResume =
Rx<Option<ParsedResumeDetails>>(none());
Future<Either<DioError, ParsedResumeDetails>> parseResumeToAPI(
String fileName,
{User? user}) async {
var result = await resumeParserRepo.getResumeDetailsAfterParsing(
fileName,
user: user,
);
return result.fold(
(l) => Left(l),
(newParsedResume) async {
error.value = none();
parsedResume.value = some(newParsedResume);
update();
return Right(newParsedResume);
},
);
}
}
and here's my json model in ResumeParserTestUtil:
class ResumeParserTestUtil {
static String fileName = "12989801ahsduiabsdui9123ajd.pdf";
static ParsedResumeDetails parsedResumeDetailsFunction(
Map<String, dynamic> response,
{User? user}) {
var userSkills = response['data']['userSkills'] == null
? [PublicUserSkill.empty()]
: List.from(response['data']['userSkills'])
.map((e) => PublicUserSkill.fromJson(e["skill"]))
.toList();
var userEducations = response['data']['educations'] == null
? [EducationParsed.empty()]
: List.from(response['data']['educations'])
.map((e) => EducationParsed.fromJson(e))
.toList();
var experiences = response['data']['experiences'] == null
? [ExperiencesParsed.empty()]
: List.from(response['data']['experiences'])
.map((e) => ExperiencesParsed.fromJson(e))
.toList();
return ParsedResumeDetails(
user: user,
userSkills:
userSkills.map(mapPublicUserSkillToSkillWithUserSkill).toList(),
userEducation: userEducations,
userWorkExperience: experiences,
);
}
static Map<String, dynamic> parsedResumeDetailsModel1 = {
"data": {
"experiences": [
{
"startDate": null,
"endDate": null,
"isPresent": false,
"organization": "Unnamed company",
"type": "WORK"
}
],
"userSkills": [
{
"skill": {
"id": "7963a547-3980-47d6-8ffc-c9e311152d9b",
"name": "Bachelors Degree > Bachelors Degree Economics",
"popularity": "0",
"flagRecount": false,
"createdAt": null,
"updatedAt": null,
},
},
{
"skill": {
"id": "05516ee5-1706-4296-aaa3-f3386767dec6",
"name":
"Bachelors Degree > Bachelors Degree Information Engineering and Media",
"popularity": "0",
"flagRecount": false,
"createdAt": null,
"updatedAt": null,
}
},
{
"skill": {
"id": "0baaa115-a770-42f5-ad54-291ffa42a11c",
"name": "Bachelors Degree > Bachelors Degree Literature",
"popularity": "0",
"flagRecount": false,
"createdAt": null,
"updatedAt": null
}
},
{
"skill": {
"id": "7a4ca05f-8d75-44c5-b012-5a0298160903",
"name": "Bachelors Degree > Bachelors Degree Mathematics",
"popularity": "0",
"flagRecount": false,
"createdAt": null,
"updatedAt": null,
},
},
{
"skill": {
"id": "b29215d5-c3cf-4b62-82df-2ee5db1c160c",
"name": "Bachelors Degree > Bachelors Degree history",
"popularity": "0",
"flagRecount": false,
"createdAt": null,
"updatedAt": null
}
}
],
"educations": [
{
"startDate": null,
"endDate": null,
"type": "EDUCATION",
"isPresent": true,
"study": {
"id": "572502d1-fb5c-4876-8985-2c4278b98a8b",
"name":
"Information Engineering and Media, history, Economics, Literature, Mathematics",
"createdAt": "",
"updatedAt": ""
},
"school": {
"id": "f54c85dd-f51e-4715-a393-dbcea6edbed7",
"name": "Adamson University",
"domain": "adamson.edu.ph",
"website": "http://www.adamson.edu.ph/",
"state": null,
"type": null,
"CountryCode": "PH",
"createdAt": null,
"updatedAt": null
},
"degree": {
"id": "63dd0edf-9193-4ac0-b693-ae561873e4a3",
"name": "Bachelor",
"createdAt": "",
"updatedAt": ""
}
},
{
"startDate": null,
"endDate": null,
"type": "EDUCATION",
"isPresent": true,
"school": {
"id": "1dedeca8-154b-4e8f-a867-d359616d996c",
"name": "Adipala Junior High School",
"domain": null,
"website": null,
"state": null,
"type": null,
"CountryCode": null,
"createdAt": "",
"updatedAt": null
}
},
{
"startDate": null,
"endDate": null,
"type": "EDUCATION",
"isPresent": true,
"school": {
"id": "38420130-dac4-4a3c-a1bc-cea4777054c1",
"name": "Unnamed school",
"domain": null,
"website": null,
"state": null,
"type": null,
"CountryCode": null,
"createdAt": null,
"updatedAt": null
}
}
]
}
};
}
and this was the result:
Expected: Some:<Some(ParsedResumeDetails([EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION)], [ExperiencesParsed(false, null, Unnamed company, null, WORK)], [Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill'], null))>
Actual: Some:<Some(ParsedResumeDetails([EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION)], [ExperiencesParsed(false, null, Unnamed company, null, WORK)], [Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill'], null))>
package:test_api
✖ Upload resume that uploaded into API:
~succeed state~ api get response and parsed it into model JSON "ParsedDetailsResume"
Exited (1)
Any thoughts on this? Thanks!

Ran into same issue trying test async call, where it was failing because I set expected value wrapped in a Future.value()
Solution in this case is to :
extract the value from the async call first with await
then do the check on raw value, without any notion of Future<>
eg:
test('test SomeService()', () async {
final actual = await someService.getSomeList();
expect(actual, []);
});

Related

MondoDB $locate

I have two collections, a policy collection, and a person collection
The Policy looks something like this:
[{
"_id": {
"$oid": "61169375e2145bbfd73dedbe"
},
"PolicyNumber": {
"Identifier": "A56B096A",
"Sequence": 1
},
"Persons": {
"61169362982ac4e8ae2ad768": null,
"60de07a8dc031e91ac5f35c0": null
},
}]
The Person:
[{
"_id": {
"$oid": "5f0c6d087937e0000145e5c3"
},
"UniqueCode": "PER0004",
"PassportExpiryDate": null,
"Age": 35,
"Gender": "M",
"Nationality": null,
"LanguageCode": null,
"Name": "NAME",
"Surname": "SURNAME",
"Initials": null,
"ContactDetails": {
"Addresses": {
"physicalAddress": {
"AddressType": null,
"UnitNumber": null,
"UnitName": null,
"PoBox": null,
"StreetNumber": null,
"StreetName": null,
"Suburb": null,
"Town": null,
"PostalCode": "7100",
"Country": null,
"Coordinates": null,
"InitialCenter": null
}
},
"EmailAddresses": {
"emailAddress": "EMAIL#EMAIL.COM"
},
"TelephoneNumbers": {
"cellphone": "0000000000"
},
"PreferredCommunicationMethod": "SMS"
},
"BankingDetails": [],
"Statistics": null,
"Imported": false,
"ImportReference": null
}]
I have tried various options with $locate, $let, $convert, etc to enable me to join the two collections on 'Persons' using the Policy collections as the entry point.
I know this is probably fundamentals, but I'm n SQL guy who got dumped with a MongoDB conversion.
Any assistance will be appreciated

My Parse Server API Request is returning empty {}

i use Back4app that uses Parse Server and node.js (axios module), to implement calls for API-football. I am getting a 200 sucess response code, running the template code as below, but it is always returning an empty {} response (Insomnia).
Thanks in advance for any help.
Parse.Cloud.define("next50", (request)=>{
const axios = require("axios");
const options = {
method: 'GET',
url: 'https://api-football-v1.p.rapidapi.com/v3/fixtures',
params: {next:'50'},
headers: {
'X-RapidAPI-Key': 'd69302225emshdf770c890926efdp19ca04jsn08d2244e2253',
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
}
};
axios.request(options).then( function (response) {
return response.data;
}).catch(function (error) {
return error;
});
});
I read axios documentation carefully and implemented a code that works, returning the correct JSON response.
here it is:
Parse.Cloud.define("next50", (request)=>{
const axios = require("axios");
const options = {
method: 'GET',
url: 'https://api-football-v1.p.rapidapi.com/v3/fixtures',
params: {next:'50'},
headers: {
'X-RapidAPI-Key': 'd69302225emshdf770c890926efdp19ca04jsn08d2244e2253',
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
}
};
var result = axios.request(options).then( function (response) {
return (response.data);
}).catch(function (error) {
return(error);
});
return (result);//👍✔
});
here is the response:
{
"result": {
"get": "fixtures",
"parameters": {
"next": "50"
},
"errors": [],
"results": 50,
"paging": {
"current": 1,
"total": 1
},
"response": [
{
"fixture": {
"id": 841439,
"referee": null,
"timezone": "UTC",
"date": "2022-11-06T11:00:00+00:00",
"timestamp": 1667732400,
"periods": {
"first": null,
"second": null
},
"venue": {
"id": 7699,
"name": "Salaspils sporta nama stadions",
"city": "Salaspils"
},
"status": {
"long": "Not Started",
"short": "NS",
"elapsed": null
}
},
"league": {
"id": 365,
"name": "Virsliga",
"country": "Latvia",
"logo": "https://media.api-sports.io/football/leagues/365.png",
"flag": "https://media.api-sports.io/flags/lv.svg",
"season": 2022,
"round": "Regular Season - 35"
},
"teams": {
"home": {
"id": 4143,
"name": "Super Nova",
"logo": "https://media.api-sports.io/football/teams/4143.png",
"winner": null
},
"away": {
"id": 4153,
"name": "Valmiera / BSS",
"logo": "https://media.api-sports.io/football/teams/4153.png",
"winner": null
}
},
"goals": {
"home": null,
"away": null
},
"score": {
"halftime": {
"home": null,
"away": null
},
"fulltime": {
"home": null,
"away": null
},
"extratime": {
"home": null,
"away": null
},
"penalty": {
"home": null,
"away": null
}
}
},
{
"fixture": {
"id": 841440,
"referee": null,
"timezone": "UTC",
"date": "2022-11-06T11:00:00+00:00",
"timestamp": 1667732400,
"periods": {
"first": null,
"second": null
},
"venue": {
"id": null,
"name": "LNK Sporta Parks",
"city": "Riga"
},
"status": {
"long": "Not Started",
"short": "NS",
"elapsed": null
}
},
"league": {
"id": 365,
"name": "Virsliga",
"country": "Latvia",
"logo": "https://media.api-sports.io/football/leagues/365.png",
"flag": "https://media.api-sports.io/flags/lv.svg",
"season": 2022,
"round": "Regular Season - 35"
},
"teams": {
"home": {
"id": 4160,
"name": "Rīgas FS",
"logo": "https://media.api-sports.io/football/teams/4160.png",
"winner": null
},
"away": {
"id": 661,
"name": "FK Liepaja",
"logo": "https://media.api-sports.io/football/teams/661.png",
"winner": null
}
},
"goals": {
"home": null,
"away": null
},
"score": {
"halftime": {
"home": null,
"away": null
},
"fulltime": {
"home": null,
"away": null
},
"extratime": {
"home": null,
"away": null
},
"penalty": {
"home": null,
"away": null
}
}
},
{
best regards for all.

how to update the first object in the array of quarterFinals that matches some mongoDB condition?

I have the document below and I need to iterate through the quarterFinals array and update the first null address property I find to '123'
{
"data": {
"createTournament": {
"_id": "613122d0c7befdeef3b0b571",
"title": "Jogo de truco",
"description": "",
"location": "Batalha na rua",
"type": "Battle",
"players": [],
"status": "PENDING",
"size": 8,
"entryFee": 1,
"prizePool": 20,
"currency": "USD",
"startDate": "2021-09-01",
"endDate": "2021-09-01",
"rounds": {
"quarterFinals": [{
"id": "9fb6f9ca-c06a-4972-b140-0f2425a90707",
"arena": "",
"firstParticipant": {
"address": null,
"battlesWon": 0
},
"secondParticipant": {
"address": null,
"battlesWon": 0
}
}]
}
}
}
}
One way of doing this is
exports.updateData = async (tournamentID,address)=>{
return await db_collection.updateOne({id:tournamentId,rounds:{$elemMatch:{quarterfinals.address:null}}},{$push:{address:address});
};

how to return just one object from an array that is inside a collection with the mongo_dart

I currently have this collection below, and I need a way to return only one item from an internal array (an item from the "pontosGastronomicos" array), only the object, I don't have much experience with mongodb. I'm developing an application and AngularDart and the backend in Angel, application is already working, I just need an optimized way to do this.
// 1
{
"_id": ObjectId("6025b13eab1951094272d007"),
"id": "03a091e2-fa67-4132-9237-f5b9ed3dbb39",
"dataCadastro": "2021-02-11 19:35:41.998",
"link": null,
"icon": "icon-pizza-1",
"ativo": true,
"order": NumberInt("0"),
...
"pontosGastronomicos": [
{
"id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31",
"infos": [
{
"id": "925ed160-9276-4046-87a2-d1f37547f7cb",
"title": "BAR DA BOCA",
"lang": "pt",
"content": "Ótima experiência com o melhor chope de Rio das Ostras"
},
{
"id": "abc2ef60-4807-4b16-8d3e-95223abe0524",
"title": "BAR DA BOCA",
"lang": "en",
"content": "Great experience with the best draft beer in Rio das Ostras"
}
],
"midias": [
{
"id": "d54435d2-2fe3-4ea1-aa04-0ccdfade4c9f",
"title": "experimente-praias-1",
"description": "experimente-praias-1.jpg",
"dataCadastro": "2021-02-10 14:23:23.224",
"fisicalFilename": "acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"originalFilename": "experimente-praias-1.jpg",
"link": "http://localhost:4002/storage/turismo/midias/acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"mimeType": "image/jpeg",
"tipo": null
}
],
"ativo": true,
"dataCadastro": "2021-02-11 19:51:26.702",
"order": NumberInt("0"),
"link": null,
"email": "bardaboca#yahoo.com.br",
"logradouro": "Rua Teresópolis",
"bairro": "Boca da Barra",
"numero": "69",
"telefone1": "2227641671 ",
"telefone2": "22998578550",
"horarioFuncionamento": "10h as 20h",
"latitude": null,
"longitude": null,
"categoria": null,
"logo": null,
"whatsapp": null,
"tipoDeCozinha": null,
"capacidade": null,
"site": null,
"facebook": null,
"youtube": null,
"instagram": null,
"observacao": null,
}
]
}
I need to make a request that brings me just a "pontosGastronomicos" by id, i currently do this via terminal:
db.pontosGastronomicos.find(
{"pontosGastronomicos.id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31"},
{_id: 0, pontosGastronomicos: {$elemMatch: {id: "208a3f93-9fcb-4db7-ac44-bb11b86a2d31"}}});
the result is this:
{
"pontosGastronomicos": [
{
"id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31",
"infos": [
{
"id": "925ed160-9276-4046-87a2-d1f37547f7cb",
"title": "BAR DA BOCA",
"lang": "pt",
"content": "Ótima experiência com o melhor chope de Rio das Ostras"
},
{
"id": "abc2ef60-4807-4b16-8d3e-95223abe0524",
"title": "BAR DA BOCA",
"lang": "en",
"content": "Great experience with the best draft beer in Rio das Ostras"
}
],
"midias": [
{
"id": "d54435d2-2fe3-4ea1-aa04-0ccdfade4c9f",
"title": "experimente-praias-1",
"description": "experimente-praias-1.jpg",
"dataCadastro": "2021-02-10 14:23:23.224",
"fisicalFilename": "acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"originalFilename": "experimente-praias-1.jpg",
"link": "http://localhost:4002/storage/turismo/midias/acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"mimeType": "image/jpeg",
"tipo": null
}
],
"ativo": true,
"dataCadastro": "2021-02-11 19:51:26.702",
"order": NumberInt("0"),
"link": null,
"email": "bardaboca#yahoo.com.br",
"logradouro": "Rua Teresópolis",
"bairro": "Boca da Barra",
"numero": "69",
"telefone1": "2227641671 ",
"telefone2": "22998578550",
"horarioFuncionamento": "10h as 20h",
"latitude": null,
"longitude": null,
"categoria": null,
"logo": null,
"whatsapp": null,
"tipoDeCozinha": null,
"capacidade": null,
"site": null,
"facebook": null,
"youtube": null,
"instagram": null,
"observacao": null,
}
]
}
how to return just one object from an array that is inside a collection with the mongo_dart
I would like the result to be like this
{
"id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31",
"infos": [
{
"id": "925ed160-9276-4046-87a2-d1f37547f7cb",
"title": "BAR DA BOCA",
"lang": "pt",
"content": "Ótima experiência com o melhor chope de Rio das Ostras"
},
{
"id": "abc2ef60-4807-4b16-8d3e-95223abe0524",
"title": "BAR DA BOCA",
"lang": "en",
"content": "Great experience with the best draft beer in Rio das Ostras"
}
],
"midias": [
{
"id": "d54435d2-2fe3-4ea1-aa04-0ccdfade4c9f",
"title": "experimente-praias-1",
"description": "experimente-praias-1.jpg",
"dataCadastro": "2021-02-10 14:23:23.224",
"fisicalFilename": "acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"originalFilename": "experimente-praias-1.jpg",
"link": "http://localhost:4002/storage/turismo/midias/acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"mimeType": "image/jpeg",
"tipo": null
}
],
"ativo": true,
"dataCadastro": "2021-02-11 19:51:26.702",
"order": NumberInt("0"),
"link": null,
"email": "bardaboca#yahoo.com.br",
"logradouro": "Rua Teresópolis",
"bairro": "Boca da Barra",
"numero": "69",
"telefone1": "2227641671 ",
"telefone2": "22998578550",
"horarioFuncionamento": "10h as 20h",
"latitude": null,
"longitude": null,
"categoria": null,
"logo": null,
"whatsapp": null,
"tipoDeCozinha": null,
"capacidade": null,
"site": null,
"facebook": null,
"youtube": null,
"instagram": null,
"observacao": null,
}
I get the answer on github, for others who have this difficulty follow the answer:
final cursor = db.collection(collection).modernAggregateCursor([
{
r'$replaceRoot': {
'newRoot': {
r'$arrayElemAt': [
{
r'$filter': {
'input': r'$pontosGastronomicos',
'as': 'pontosGastronomicos',
'cond': {
/* resolve to a boolean value and determine if an element should be included in the output array. */
r'$eq': [r'$$pontosGastronomicos.id', '208a3f93-9fcb-4db7-ac44-bb11b86a2d31']
}
}
},
0 /* the element at the specified array index */
]
}
}
}
]);
result = await cursor.nextObject();
await cursor.close();
/*result = await db.collection(collection).modernFindOne(filter: {
'pontosGastronomicos': {
r'$elemMatch': {'id': '208a3f93-9fcb-4db7-ac44-bb11b86a2d31'}
}
}, projection: {
'_id': 0,
'pontosGastronomicos': {
r'$elemMatch': {'id': '208a3f93-9fcb-4db7-ac44-bb11b86a2d31'}
}
});*/
print(result);

Adding Full Contact details in Ionic Framework

In the official documentation of contacts in ngCordova, it only says $scope.contactForm, in other example (link below) only show how to add display name. how can I add fields like phone number email, address etc...
module.controller('MyCtrl', function($scope, $cordovaContacts) {
$scope.addContact = function() {
$cordovaContacts.save($scope.contactForm).then(function(result) {
// Contact saved
}, function(err) {
// Contact error
});
};
// Many more features will be added shortly
});
https://blog.nraboy.com/2014/11/create-delete-search-contacts-ionic-framework/
http://ngcordova.com/docs/plugins/contacts/
$scope.contactForm = {
"displayName": "jones",
"name": {
"givenName": "jones",
"formatted": "jones "
},
"nickname": null,
"phoneNumbers": [
{
"value": "99999999999",
"type": "mobile"
}
],
"emails": [
{
"value": "xddf#dd.com",
"type": "home"
}
],
"addresses": [
{
"type": "home",
"formatted": "This Address, An Address",
"streetAddress": "This Address, An Address"
}
],
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": null,
"categories": null,
"urls": null
}