How to trigger component event in angular dart tests? - unit-testing

I'm using angular_test.dart to test my components. I want to test that clicking on a particular <li> will mark it as selected.
multiple_choice_quiz_component.html
<div>
<div class="contain-center">
<h1>{{quiz.getDescription}}</h1>
</div>
<div class="contain-center">
<ul>
<li *ngFor="let answer of quiz.getChoiceList"
(click)="onSelect(answer)"
[class.selected]="answer == selectedAnswer"
[class.correct]="correctAnswer && answer == selectedAnswer"
[class.incorrect]="!correctAnswer && answer == selectedAnswer"
>
{{answer}}
</li>
</ul>
</div>
</div>
multiple_choice_quiz_component.dart
class MultipleChoiceQuizComponent
{
String selectedAnswer;
String description;
bool correctAnswer = false;
Quiz quiz;
MultipleChoiceQuizComponent(QuizService quizService)
{
this.quiz = quizService.getQuiz();
}
void onSelect(String answer)
{
selectedAnswer = answer;
this.correctAnswer = this.quiz.isAnswer(answer);
}
}
test.dart
...
import 'package:angular_test/angular_test.dart';
....
group('My Tests', () {
test('should change li element to selected', () async {
var bed = new NgTestBed<MultipleChoiceQuizComponent>();
var fixture = await bed.create();
await fixture.update((MultipleChoiceQuizComponent Component) {
});
});});
In my test, how can I trigger a click on let's say the second <li> and evaluate that it has the selected property? And how do I mock the quiz service and inject it to the constructor?

I thought I wasn't going to figure it out, but I did.
Using a debug html test file helped a lot. On the console I could set breakpoints. Using the console I could navigate through the methods of these objects to find out what I needed to call.
NgTestBed bed = new NgTestBed<MultipleChoiceQuizComponent>();
NgTestFixture fixture = await bed.create();
Element incorrectAnswer = fixture.rootElement.querySelector('.quiz-choice:nth-child(2)');
incorrectAnswer.dispatchEvent(new MouseEvent('click'));
bool hasClass = incorrectAnswer.classes.contains('incorrect');
expect(true, hasClass);

You can use PageObjects to interact with the page:
https://github.com/google/pageloader

Related

I need to Delete any object from my DRF / django connected database through angular 13

I am getting the id which i have to delete but the last line of service.ts that is of delete method is not getting executed...
the files and code snippets I used are : -
COMPONENT.HTML
<li *ngFor="let source of sources$ | async | filter: filterTerm">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{source.name}}</h5>
<p>URL:- <a href ='{{source.url}}'>{{source.url}}</a></p>
<a class="btn btn-primary" href='fetch/{{source.id}}' role="button">fetch</a>
<button class="btn btn-primary" (click)="deleteSource(source.id)">delete </button>
<br>
</div>
</div>
</li>
I tried to console the id geeting from html and the Id i am getting is correct.
//component.ts
export class SourcesComponent implements OnInit {
filterTerm!: string;
sources$ !: Observable<sources[]>;
// deletedSource !: sources;
constructor(private sourcesService: SourcesService) { }
// prepareDeleteSource(deleteSource: sources){
// this.deletedSource = deleteSource;
// }
ngOnInit(): void {
this.Source();
}
Source(){
this.sources$ = this.sourcesService.Sources()
}
deleteSource(id : string){
console.log(id)
this.sourcesService.deleteSource(id);
}
//service.ts
export class SourcesService {
API_URL = 'http://127.0.0.1:8000/sourceapi';
constructor(private http: HttpClient) { }
// let csrf = this._cookieService.get("csrftoken");
// if (typeof(csrf) === 'undefined') {
// csrf = '';
// }
/** GET sources from the server */
Sources() : Observable<sources[]> {
return this.http.get<sources[]>(this.API_URL,);
}
/** POST: add a new source to the server */
addSource(source : sources[]): Observable<sources[]>{
return this.http.post<sources[]> (this.API_URL, source);
//console.log(user);
}
deleteSource(id: string): Observable<number>{
let httpheaders=new HttpHeaders()
.set('Content-type','application/Json');
let options={
headers:httpheaders
};
console.log(id)
return this.http.delete<number>(this.API_URL +'/'+id)
}
}
Angular HTTP functions return cold observables. This means that this.http.delete<number>(this.API_URL +'/'+id) will return an observable, which will not do anything unless someone subscribes to it. So no HTTP call will be performed, since no one is watching the result.
If you do not want to use the result of this call, you have different options to trigger a subscription.
simply call subscribe on the observable:
deleteSource(id : string){
console.log(id)
this.sourcesService.deleteSource(id).subscribe();
}
Convert it to a promise and await it (or don't, if not needed) using lastValueFrom:
async deleteSource(id : string){
console.log(id)
await lastValueFrom(this.sourcesService.deleteSource(id));
}

How to update product quantity after adding product to cart?

I am working on a shopping cart project which is developed using angular and django. I want to update the qty of product when adding a product. but now the qty is updated when page is refreshed.
Below code i have been tried so far.
Home.Component.ts:
async ngOnInit() {
await this.getUpdatedCart();}
ngOnDestroy() {
this.subscription.unsubscribe();}
async getUpdatedCart() {
await this.cartService.getCart(this.products);
this.subscription = this.cartService.updatedCart
.subscribe(cart => {
this.cart = cart;
console.log('cart', this.cart);
});
}
shopping-cart.services.ts:
updatedCart = new BehaviorSubject<any>('');
async getCart(product) {
const cartId = JSON.parse(localStorage.getItem('cartId'));
if (cartId) {
this.http.get(this.globalService.baseUrl + 'shopping-cart/' + cartId + '/').subscribe(data => this.updatedCart.next(data));
}}
product-card.component.ts:
export class ProductCardComponent {
#Input('product') product;
#Input('shopping-cart') shoppingCart;
constructor(private cartService: ShoppingCartService,
private homeComponent: HomeComponent) {
}
async addToCart(product) {
await this.cartService.addProductToCart(product);
await this.homeComponent.getUpdatedCart();
}
getQuantity() {
if (!this.shoppingCart) {
return 0;
}
const item = this.shoppingCart.carts;
for (let i = 0; i < item.length; i++) {
if (item[i].product === this.product.id) {
return item[i].qty;
}
}
return 0;}}
product-card.component.html:
<div class="card-footer">
<button (click)="addToCart(product) " class="btn btn-primary btn-
block">Add to cart</button>
<div>{{getQuantity() }}</div>
</div>
</div>
I want when user click "add to cart" button then the quantity will be updated.
but quantity is updated after i click the button twice.
Use Subjects (Example) in this case. Make a service in shopping-cart.services.ts and fetch cart data from there. You will get the updated cart on subscription of that cart.

Angular modal template not displaying

I'm somewhat new to Angular. I am trying to display a Bootstap 3 modal dialog when an invalid user role is detected. I cannot get my modal template to display. The behavior seems to work i.e. I can dismiss the faded overlay..I just don't see the actual modal template.
Bootstrap 3
AngularJS 1.0.7
AngularJS UI Bootstrap 0.6.0
Controller
gsApp.controller('MainController', ['$rootScope', '$scope', '$q', '$window', '$location', '$modal', 'ApplicationCache', 'UserService',
function MainController($rootScope, $scope, $q, $window, $location, $modal, ApplicationCache, UserService) {
$scope.userRole = "BadRole";
$scope.showBadRoleModel = function () {
var showBadRoleModelInstance = $modal.open({
templateUrl: "badRoleModal.html",
backdrop: true,
windowClass: 'modal',
controller: badRoleModalInstance,
resolve: {
items: function () {
return $scope.userRole;
}
}
});
}
var badRoleModalInstance = function($scope, $modalInstance, items){
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
}]);
HTML
<div class="row" ng-controller="MainController">
<script type="text/ng-template" id="badRoleModal.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<h2>body</h2>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn" ng-click="showBadRoleModel()">Show bad role modal</button>
</div>
AngularJs UI Bootstrap doesn't work with Bootstrap 3 yet.
See more details here: https://github.com/angular-ui/bootstrap/issues/331
Here's a reusable Angular directive that will hide and show a Bootstrap 3 (or 2.x) modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question. Here are some related links: Simple Angular Directive for Bootstrap Modal and https://stackoverflow.com/a/19668616/1009125
Hope this helps.

AngularJS with list

I'm doing an employees list that is loaded from SQLite database. I don't know why my list is empty, but I can see via JSON.stringify that data is comming.
I'm using AngularJS and Cordova Framework. Debugging with Ripple.
listEmployees.html
<div data-role="page" apply-jq-mobile>
<div data-theme="a" data-role="header">
<h3>
Header
</h3>
</div>
<div data-role="content">
<div class="ui-grid-a">
<div class="ui-block-a">
</div>
<div class="ui-block-b">
<a data-role="button" href="#/new" data-icon="plus" data-iconpos="left">
New
</a>
</div>
</div>
<input type="text" ng-model="search" class="search-query" placeholder="Search">
<ul data-role="listview" data-divider-theme="b" data-inset="true">
<li data-role="list-divider" role="heading">
Employees
</li>
<li data-theme="c" ng-repeat="employee in employees">
{{employee.name}}
</li>
</ul>
</div>
</div>
EmployeeCtrl
function EmployeeCtrl($scope, Employee){
$scope.employees = Employee.getAllEmployees();
$scope.saveEmployee = function(id) {
if(id){
//TODO
} else {
Employee.addEmployee($scope.employee);
}
}
}
Employee
app.factory('Employee', function() {
var data = {};
data.addEmployee = function(_employee, callback) {
var employee = new Employee();
employee = _employee;
DbService.db.employees.add(employee);
DbService.db.saveChanges(callback);
}
data.getAllEmployees = function() {
DbService.db.employees.toArray(function(employees) {
console.log(JSON.stringify(employees));
return employees;
});
};
return data;
});
I think you need to use promises. Your call to db is asynchronous and therefore view is getting rendered before your data arrives.
data.getAllEmployees = function() {
var $d = $q.defer();
DbService.db.employees.toArray(function(employees) {
console.log(JSON.stringify(employees));
$d.resolve(employees);
});
return $d.promise;
};
Angular templating system wait for all the promises to get resolved before rendering. So I think this will solve your problem.
So, I solved it.
function EmployeeCtrl($scope, Employee){
Employee.getAllEmployees(function(employees){
$scope.employees = employees;
$scope.$apply();
});
}
.
app.factory('Employee', function() {
var data = {};
data.getAllEmployees = function(callback) {
DbService.db.employees.toArray(function(employees) {
callback(employees);
});
};
return data;
});
Thank you all!

if statement inside knockout array

Im trying to load a knockout observable array 25 items at a time using a count variable. The idea is that when you click a button you get another 25 items in the list. Sounds simple but Im useless with knockout.
I tried calling $root.getCount and $parent.getCount and put getCount in my list-view div as a value but none work. I might be over thinking it. All i want to do is put a named variable into the if statement where $getCount is. help would be awesome.
<div class="list-view" >
<ul data-bind="foreach: myBigList" class="shop_list">
<!-- ko if: $index() < $getCount -->
<li class="list_row">
</li>
<!-- /ko -->
</ul>
</div>
here's my view model
$(function () {
var viewModel = {
count: ko.observable(25),
getCount: function () {
return count;
},
updateCount: function () {
count+=count;
},
};
ko.applyBindings(viewModel);
})
I'm not sure I understand what you are really trying to achieve, but I'm going to assume you already have a big list of items that you want to display in groups of 25. You can achieve that using the visible binding:
<div class="list-view" >
<ul data-bind="foreach: myBigList" class="shop_list">
<li class="list_row" data-bind="visible: $index() < $parent.count()">
</li>
</ul>
</div>
Since count is an observable, to upate it's value you need to do this:
$(function () {
function ViewModel() {
this.count = ko.observable(25);
this.updateCount = function () {
var newCount = this.count() + 25;
this.count(newCount);
};
}
ko.applyBindings(new ViewModel());
})
Since count is an observable, you must use the function syntax to return it: return count();. If you want to add 25 to the count variable each time the updateCount method is called, you will need to hardcode the value.
$(function () {
var viewModel = {
count: ko.observable(25),
getCount: function () {
return count();
},
updateCount: function () {
count()+=25;
},
};
ko.applyBindings(viewModel);
})