How to test if a function is called using open/wc testing with sinon? - karma-runner

I am new to web components, and am using LIT framework. I have been breaking my head trying to figure this out.
This is my function.
createObj() {
this.financingObj = [];
if (this.dropDownValue === common.ONCE) {
if (this.ammountEntered >= 2000 && this.ammountEntered <= 999999) {
this.financingObj.push(this.createFinancingStructure('BusinessLoan'));
}
if (this.ammountEntered >= 10000 && this.ammountEntered <= common.MAX_ALLOWED_VALUE) {
this.financingObj.push(this.createFinancingStructure('Leasing'));
}
if (this.ammountEntered >= 250000 && this.ammountEntered <= common.MAX_ALLOWED_VALUE) {
this.financingObj.push(this.createFinancingStructure('InvestmentLoan'));
}
if (this.ammountEntered >= 2500000 && this.ammountEntered <= common.MAX_ALLOWED_VALUE) {
this.financingObj = this.financingObj.filter(
item => item !== this.createFinancingStructure('BusinessLoan'),
);
this.financingObj.push(this.createFinancingStructure('RollOverTermLoan'));
}
} else if (this.dropDownValue === common.MULTIPLE_TIMES) {
if (this.ammountEntered >= 250000 && this.ammountEntered <= common.MAX_ALLOWED_VALUE) {
this.financingObj.push(this.createFinancingStructure('InvestmentLoan'));
}
if (this.ammountEntered >= 2500000 && this.ammountEntered <= common.MAX_ALLOWED_VALUE) {
this.financingObj.push(
this.createFinancingStructure('RollOverTermLoan'),
this.createFinancingStructure('RollOverRevolving'),
);
}
}
}
And this is my test case
it('should call createObjForInvest when invest product is selected', () => {
const spy = sinon.spy(element, 'createObj');
spy();
sinon.assert.called(spy);
});
I see the function gets called, but I am getting the following error.

Related

A value of type 'Null' can't be assigned to a variable of type 'double'

Hello I have a connect four game who worked before null safety but I try to make the migration, but I have a problem with scores[i] = null; I can't write like that but without it I have a freeze when CPU is certain to loose
int _compute(Board board, int step, int deepness, List<double> scores) {
for (var i = 0; i < 7; ++i) {
final boardCopy = board.clone();
final target = boardCopy.getColumnTarget(i);
if (target == -1) {
scores[i] = null; // <<<---- HERE I CAN'T USE NULL
continue;
}
final coordinate = Coordinate(i, target);
boardCopy.setBox(coordinate, player);
if (boardCopy.checkWinner(coordinate, player)) {
scores[i] += deepness / (step + 1);
continue;
}
for (var j = 0; j < 7; ++j) {
final target = boardCopy.getColumnTarget(j);
if (target == -1) {
continue;
}
final coordinate = Coordinate(j, target);
boardCopy.setBox(coordinate, otherPlayer);
if (boardCopy.checkWinner(coordinate, otherPlayer)) {
scores[i] -= deepness / (step + 1);
continue;
}
if (step + 1 < deepness) {
_compute(board, step + 1, deepness, scores);
}
}
}
return _getBestScoreIndex(scores);
}
int _getBestScoreIndex(List<double> scores) {
int bestScoreIndex = scores.indexWhere((s) => s != null);
scores.asMap().forEach((index, score) {
if (score != null &&
(score > scores[bestScoreIndex] ||
(score == scores[bestScoreIndex] && _random.nextBool()))) {
bestScoreIndex = index;
}
});
return bestScoreIndex;
}
if I use List<double?>
int _compute(Board board, int step, int deepness, List<double?> scores) {
for (var i = 0; i < 7; ++i) {
final boardCopy = board.clone();
final target = boardCopy.getColumnTarget(i);
if (target == -1) {
scores[i] = null;
continue;
}
final coordinate = Coordinate(i, target);
boardCopy.setBox(coordinate, player);
if (boardCopy.checkWinner(coordinate, player)) {
scores[i] += deepness / (step + 1);//<<<---- HERE I CAN'T USE +=
continue;
}
for (var j = 0; j < 7; ++j) {
final target = boardCopy.getColumnTarget(j);
if (target == -1) {
continue;
}
final coordinate = Coordinate(j, target);
boardCopy.setBox(coordinate, otherPlayer);
if (boardCopy.checkWinner(coordinate, otherPlayer)) {
scores[i] -= deepness / (step + 1); //<<<---- HERE I CAN'T USE -=
continue;
}
if (step + 1 < deepness) {
_compute(board, step + 1, deepness, scores);
}
}
}
return _getBestScoreIndex(scores);
}
int _getBestScoreIndex(List<double?> scores) {
int bestScoreIndex = scores.indexWhere((s) => s != null);
scores.asMap().forEach((index, score) {
if (score != null && // <<<---- HERE I CAN'T USE score !=
(score > scores[bestScoreIndex] || // <<<---- HERE I CAN'T USE score >
(score == scores[bestScoreIndex] && _random.nextBool()))) {
bestScoreIndex = index;
}
});
return bestScoreIndex;
}
The issue with your code is that in the function definition you have defined the data type of score variable as List<double>. Due to which you get an error on assigning score[i] = null. To fix this use data type of score as List<double?>
i believe the param scores is a type-defined value and it has a double, which is a non null value. So you can't assign null to double as it has the type of value assigned.
You can make it double as an optional value, like a List<double?>. but with this, the values in the list will be optional and you need to force unwrap or do null check before using them.

Error running simulation — An unknown error occurred

{
"__name__":"/databases/(default)/documents/users/mfBBtfSX91YS9mXrkmEDTksA0712/sold/mfBBtfSX91YS9mXrkmEDTksA0712-hanSW0s5MxOOENWnc5T1cLinekj2/invoice/WhdEi2W83GtjDjowi6MV",
"id":"WhdEi2W83GtjDjowi6MV",
"data":{
"id":"db1a01a0-4da5-11ec-a579-c31f34aa6119",
"total":80,
"quotations":[
{
"id":"c595e610-46ab-11ec-b8ad-d56159e1778c",
"title":"anda",
"measuremntUnit":"kg",
"rate":35,
"quantity":2,
"isSelected":false,
"index":1
},
{
"id":"c595e610-46ab-11ec-b8ad-d56159e1778c",
"title":"biscuit",
"measuremntUnit":"packet",
"rate":10,
"quantity":1,
"isSelected":true,
"index":7}
],
"sellerEmail":"ku1438693#gmail.com",
"sellerUserId":"mfBBtfSX91YS9mXrkmEDTksA0712",
"sellerDisplayName":" Lila Kunwar",
"buyerUserId":"hanSW0s5MxOOENWnc5T1cLinekj2",
"buyerDisplayName":"saugat thapa",
"buyerEmail":"nexus.saugat26#gmail.com",
"sellerPhotoUrl":"https://lh3.googleusercontent.com/a/AATXAJ",
"buyerPhotUrl":"https://lh3.googleusercontent.com/a/AATXAJ"
}}
i am trying to check whether above data can insert into firestore given that the following is the security rule. however i get error Error running simulation — An unknown error occurred.
match /users/{userId}{
match /sold/{soldId}/{document=**}{
function isAuthed(){
return request.auth != null && request.auth.uid == userId;
}
function isSeller(){
return request.auth.uid == resource.data.sellerUserId ||
request.auth.uid == resource.data.buyerUserId;
}
function isApproved() {
return request.resource.data.isApproved == false;
// || request.resource.data.reviewed == "false"
}
function quotations(){
return request.resource.data.quotations;
}
function isOtherThanQuotations(){
return
isValidStringInput(request.resource.data.buyerUserId) &&
isValidStringInput(request.resource.data.buyerEmail) &&
isValidStringInput(request.resource.data.buyerPhotoUrl) &&
isValidStringInput(request.resource.data.buyerDisplayName) &&
isValidStringInput(request.resource.data.sellerUserId)&&
isValidStringInput(request.resource.data.buyerEmail) &&
isValidStringInput(request.resource.data.buyerPhotoUrl) &&
isValidStringInput(request.resource.data.buyerDisplayName) &&
isValidNumber(request.resource.data.total) &&
// isApproved() &&
request.resource.data.createdAt == request.time;
}
function isSelected() {
return request.resource.data.isSelected == false;
// || request.resource.data.reviewed == "false"
}
function isValidQuotation(item) {
return quotations()[item].keys().hasAll(
[
'title',
'rate',
'quantity',
'measuremntUnit',
'isSelected',
'index',
])
&& isValidStringInput(quotations()[item].title, 200)
&& isValidNumber(quotations()[item].rate)
&& isValidNumber(quotations()[item].quantity)
&& isValidStringInput(quotations()[item].measuremntUnit, 200)
&& isValidNumber(quotations()[item].index)
&& isSelected();
}
function isValidStringInput(input, maxSize) {
return input is string
&& input.size() > 0
&& input.size() <= maxSize;
}
function isValidNumber(input) {
return input is int
|| input.matches('^[0-9]+$');
}
allow read: if isSeller();
allow write: if isAuthed()
&& quotations().size() >= 1
&& quotations().size() <= 10
&& isOtherThanQuotations()
&& isValidQuotation(0)
&& (quotations().size() < 2 || isValidquotation(1) )
&& (quotations().size() < 3 || isValidquotation(2) )
&& (quotations().size() < 4 || isValidquotation(3) )
&& (quotations().size() < 5 || isValidquotation(4) )
&& (quotations().size() < 6 || isValidquotation(5) )
&& (quotations().size() < 7 || isValidquotation(6) )
&& (quotations().size() < 8 || isValidquotation(7) )
&& (quotations().size() < 9 || isValidquotation(8) )
&& (quotations().size() < 10 || isValidquotation(9) )
&& (quotations().size() < 11 || isValidquotation(10) );
}
}
is it becase i have too too many functions? right now myconcern is with create only.
is it becasue the id doesnt have security rule to validate? i tried providing validation for id as well but the error still persist. i need more than 10 map in an array but this is for simplicity of testing process.

How to add range validation for year in flutter

I've tried to add year range validation it must be between 1850 to the current year. i've tried but it's not working.
Here is the code I've tried
String validateestablishedyear(String value) {
var date = new DateTime.now();
int currentYear = date.year;
int userinputValue = 0;
print('currentYear = $currentYear');
print('input value = $value');
print('value = ${value is int}');
print('value = ${value is String}');
if (value is String && value.length == 0) {
return "Established Year is Required";
} else {
userinputValue = int.parse(value);
}
if (userinputValue < 1850 && userinputValue >= currentYear) {
return "Year must be between 1850 and $currentYear";
}
return null;
}
Just change your code as below,
if (userinputValue < 1850 || userinputValue >= currentYear) {
return "Year must be between 1850 and $currentYear";
}
You're logic is wrong. you should have use || instead of &&

EF other way to Sum() new Column

i got stuck on this query that calculate the new column.
i cannot explain briefly just see the snippet code below.
from user in context.Table
select new
{
Total = user.Total,
Paid = user.Paid,
Balance = //should be Total - Paid to assign result
}
i have tried this query
var result = from a in context.EnrollmentRequests
where a.SchoolYear == SchoolYear
select new
{
a.StudentID,
Name = a.Student.FirstName + " " + a.Student.MiddleName + " " + a.Student.LastName,
Tuition = context.Miscs.Where(m => m.YearLevel == a.YearLevel && m.SchoolYear == SchoolYear && m.Term == a.Term && m.CourseID == a.CourseID)
.Select(ms => new { Amount = ms.Amount })
.Union(context.StudentCharges
.Where(s => s.YearLevel == a.YearLevel && s.SchoolYear == SchoolYear && s.Term == a.Term && s.CourseID == a.CourseID && s.StudentID == a.StudentID)
.Select(ss => new { Amount = ss.Amount }))
.Union(context.StudentSubjectTakes
.Where(st => st.StudentID == a.StudentID && st.SchoolYear == a.SchoolYear && st.Term == a.Term && st.YearLevel == a.YearLevel && st.EducationalLevel == a.Student.StudentAdvanceEducations.FirstOrDefault().EducationLevel)
.Select(st => new
{
Amount = context.SubjectOfferedFees
.Where(f => f.SubjectsOfferedID == st.SubjectsOfferedID).Sum(w => (decimal?)w.Cost ?? 0)
}))
.Select(f => f.Amount).Sum(),
PaymentMade = context.Payments.Where(p => p.SchoolYear == SchoolYear && p.Term == a.Term && p.StudentID == a.StudentID && p.PaymentDes == "Tuition Fee").Sum(sm => (decimal?)sm.Amount),
Balance = Tuition - PaymentMade //Does not exist on current context
};
but doesn't work it says that does not exist on current context.
how could this possible.
thanks. this will be helpful to anyone.
Balance = user.Total - user.Paid

Change Value of Duplicate Object in NSMutableArray?

I have the method below, which in my Blackjack app will get the value of the hand which is an NSMutableArray. The problem here is that when 2 Ace's are in a hand, it should be a 12, but because it counts Ace's as 11, it results in being 22, which then makes lowValue returned.
How can I make it so that I can check and see if the for loop has already found an Ace and if it finds another, makes the next Ace worth only 1, not 11?
Thanks!
int getHandValue(NSMutableArray *hand) {
int lowValue = 0;
int highValue = 0;
for (KCCard *aCard in hand) {
if (aCard.value == Ace) {
lowValue+= 1;
highValue+= 11;
} else if (aCard.value == Jack || aCard.value == Queen || aCard.value == King) {
lowValue += 10;
highValue += 10;
} else {
lowValue += aCard.value;
highValue += aCard.value;
}
}
return (highValue > 21) ? lowValue : highValue;
}
Perhaps you can add a boolean value before the for loop setting it initially to NO. When an Ace is found then you can break from the for loop after setting the boolean to YES, that way if you encounter another Ace && your boolean value == YES you can handle the case accordingly.
int getHandValue(NSMutableArray *hand) {
int lowValue = 0;
int highValue = 0;
BOOL isFoundAce = NO;
for (KCCard *aCard in hand) {
if (aCard.value == Ace) {
if (isFoundAce) {
lowValue+= 1;
highValue+= 1;
}
else {
lowValue+= 1;
highValue+= 11;
isFoundAce= YES;
}
} else if (aCard.value == Jack || aCard.value == Queen || aCard.value == King) {
lowValue += 10;
highValue += 10;
} else {
lowValue += aCard.value;
highValue += aCard.value;
}
}
return (highValue > 21) ? lowValue : highValue;
}
My example without a redundant code from zsxwing's example:
int getHandValue(NSMutableArray *hand) {
int cardValue = 0;
int aceCount = 0;
for (KCCard *aCard in hand) {
if (aCard.value == Ace) {
aceCount++;
cardValue += 11;
} else if (aCard.value == Jack || aCard.value == Queen || aCard.value == King) {
cardValue += 10;
} else {
cardValue += aCard.value;
}
}
while ((cardValue > 21) && (aceCount > 0)) {
cardValue -= 10;
aceCount--;
}
return cardValue;
}