Issue How to unit test (Jest here) custom validator, which has FormGroup? I’ve seen this question, but it’s about FormControl. The function to be tested. import { FormGroup } from ‘@angular/forms’; /** * @description Validate if passwords are different. *
Continue readingTag: unit-testing
How to mock Angular external Javascript object
Issue I have an angular application which only purpose is to build @angular/elements (no index.html, no app.component, etc.). Those elements are used in an .NET Mvc app which provides two kind of things I’m trying to mock in my unit
Continue readingHow to add a bean in SpringBootTest
Issue The question seems extremely simple, but strangely enough I didn’t find a solution. My question is about adding/declaring a bean in a SpringBootTest, not overriding one, nor mocking one using mockito. Here is what I got when trying the
Continue readingAngular unit testing prime ng calendar
Issue Inside a unit test, when I have a regular element I can set its value, trigger a change event and verify the form value matches like so: const hostElement = fixture.nativeElement; const userIdSelect: HTMLInputElement = hostElement.querySelector(‘select[formcontrolname=”userId”]’); userIdSelect.value = ‘myUser’;
Continue readingHow to test controller separately?
Issue I have a controller for changing some DOM from different places. The controller is: angular.module(‘myModule’).controller(‘myController’, myController); function myController() { this.addSomeClass = function() { $(‘#idOfSomeElement’).addClass(‘someClass’); }; } And It is used like this. Inside different components and html. <div id=”idOfSomeElement”></div>
Continue readingAngular 7 unit testing dependency injection not working in ngOnInit
Issue I am using Angular 7 with and Angular CLI version 7.3.4. I am unit testing a component with 2 service injections all important code is included below. I included the stub which is causing errors, the spec file, and
Continue readingTesting component in NativeScript Angular2 app
Issue I’m having issues doing a very simple component test in a NativeScript Angular 2 application. I can’t seem to just call “new Component()” and then test it like was shown in this test example. I’m trying an implementation of
Continue readingAngularJS: how to invoke event handlers and detect bindings in tests
Issue I want to write unit and e2e tests for various custom angularjs directives that add javascript event bindings to the elements they are attached to. In tests, it’s easy enough to simulate click and dblclick events using jQuery methods.
Continue readingWhat is midway testing?
Issue So I’ve heard of unit and integration testing, but I just recently heard of midway testing. It seems like the term is used most commonly in an AngularJS context. A Google query turned up very little information on the
Continue readingAngularJS: testing actual $http requests (not mocks) to get a success() or error() case…?
Issue I’ve been tasked with setting up some “Integrated Tests” (not “Unit Tests” or “UI tests” [aka. E2E/Protractor]). This integrated test is doing nothing more than testing the controller’s $http POST request to the external API, and checking for an
Continue readingHow to organize unit tests and e2e tests in AngularJS?
Issue I need to organize unit tests and end to end tests for my JavaScript Single Page Application. I’m using AngularJS Protractor/Cucumber for e2e testing and Chai for unit tests. I have e2e and unit tests in two different folders
Continue readingAngular test dependency module
Issue I am successfully unit-testing a component-under-test. I had to add some more functionality to the component – tooltips and translations. The translation service is my code and I was able to both test component-under-test with the translation service and
Continue readingWhat contents "errorMessage()" function in Angular testing docs. (see the description)
Issue I’m unable to find any source or explanations about errorMessage() function which written here: https://angular.io/guide/testing#async-test-with-fakeasync. Can you help me to sort out, what it contains? Solution The code for errorMessage() function is: // Helper function to get the error
Continue readingCannot read property 'getData' of undefined in angular
Issue could you please tell me why I am getting this error Cannot read property ‘getData’ of undefined I am trying to test my service when I try to run my test it gives me above error here is my
Continue readingunit testing of many simple *ngIf
Issue I have simply component @Component({ selector: ‘app-certificate-panel’, templateUrl: ‘./certificate.component.html’ }) export class CertificateComponent { @Input() public certificate: Certificate; } with template <h3 translate>General</h3> <x-form-row label=”{{‘Version’ | translate}}”> {{ certificate.version }} </x-form-row> <x-form-row label=”{{‘Serial Number’ | translate}}”> {{ certificate.serialNumber }}
Continue readingHow to mock an error from Observable without crashing?
Issue I have a mock service export class DataServiceStub { numbers$ = of([1,2,3,4,5,6]).pipe( switchMap((data: number[]) => { if (this._error) { return throwError(this._error); } return of(data); }); private _error: string; setError(msg: string) { this._error = msg; } } And I am
Continue readingAngular – Karma Testing – Failed: Cannot read property 'textContent' of null
Issue I have one failure when I run ‘ng test’ on my Angular 6 app: Failed: Cannot read property ‘textContent’ of null Please see sample app… SampleApp The problem appears to be with the app.component.spec.ts file. See error message below:
Continue readingHow to inject Angular 6+ service variables into app-routing.module.spec.ts and test router redirection
Issue I’m trying to test whether a user is redirected successfully if an authenticated variable is set to true. I’ve tried injecting my LoginService into a beforeEach and setting the authenticated variable to false. Then, in the unit test, setting
Continue readingGet routerLink properties from HTML in Angular unit test
Issue I have following HTML property: <ul> <li class=”nav-item” routerLinkActive=”active”> <a class=”nav-link” [routerLink]=”[‘/home’]”>Home</a> </li> </ul> I want now to get the href as a value in the unit test. So far I have in my test-case: it(‘should navigate have login
Continue readingTesting a RxJS Subject: subscribe method not getting called in the test
Issue I have a private Subject attributeNameSubject. There is a setAttributeName method that passes a string value to the subject. We get reference to that subject using the getAttributeName. I am trying to test the above code, but I always
Continue readingCan you instantiate a service manually before it is injected into a tested component?
Issue I am trying to test a component, ProfileComponent in Angular. ProfileComponent depends on AuthenticationService through injection: profile.component.ts constructor(public authenticationService: AuthenticationService) { } My ProfileComponent is simply a page, and cannot be navigated to unless the user is logged in
Continue readingAngular 6 – mock authState – valueChanges of undefined
Issue I have a service with a property and a getter. The property is set in the service constructor like this: public readonly usersMetaData: Observable<User | null>; constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore) { this.usersMetaData = this.afAuth.authState.pipe(switchMap((user: firebase.User) => {
Continue readingAngular 2 Testing – Async function call – when to use
Issue When do you use the async function in the TestBed when testing in Angular 2? When do you use this? beforeEach(() => { TestBed.configureTestingModule({ declarations: [MyModule], schemas: [NO_ERRORS_SCHEMA], }); }); And when do you use this? beforeEach(async(() => {
Continue readingHow to write unit test case for a method [Angular]
Issue I’m a beginner in Angular. I’m trying hard to learn Typescript and now I’ve been told to write unit test cases in Jasmine and Karma for every component and service I create. I’ve watched many tutorials to learn Unit
Continue readingHow do I provide ControlContainer inside an Angular component's unit test?
Issue As per the title, how can I provide ControlContainer inside an Angular unit test? The following is the error produced: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core)[ChildFormComponent -> ControlContainer]: NullInjectorError: No provider for ControlContainer! My attempt to provide ControlContainer: beforeEach(()
Continue readingangular testing a component using jasmine when the a method call is made in the html
Issue I have to test this odd situation. In my html i have: <div id=”date”> <h5> {{ showFormattedDate(myDate) }} </h5> </div> The function showFormattedDate() is defined in .ts as follows: showFormattedDate(dateToFormat: string): string { return moment(dateToFormat).format(‘HH:mm DD/M/YYYY’); } Now i’m
Continue readingAngular 8 Unit Test, Cannot set property 'valueAccessor' of null
Issue I’m trying to simply pass the test (should create – component=> toBeTruthy) for the custom component (angular component class) implemented with ControlValueAccessor. I’ve injected NgControl in constructor and pass the this keyword. constructor(@Optional() @Self() public controlDir?: NgControl) { this.controlDir.valueAccessor
Continue readingJasmine replace class while testing another class
Issue I have a plain old class, not a component, with this method that I want to test static fromJson(json: any): ClientDTO { const ret: ClientDTO = Object.assign(new ClientDTO(), json) const dp = new DateWithoutTimePipe() ret.contractStart = dp.transform(json.contractStart) ret.contractEnd =
Continue readingAngular Testing Getting Actual HTTP Response
Issue I’m new to angular unit testing. What I want to do is getting actual results from my API. I checked this documentation but as I understand, I should create mock responses. Here is my code, myService.ts: … public GetAll
Continue readingAngular: Testing Http POST method
Issue I have a simple service method that does an http post call to add a todoList: add(event: any): Observable<TodoList> { let todoListToAdd: TodoList = { name: event.target.value, listItems: []}; return this.http.post<TodoList>("https://localhost:44305/todolist", todoListToAdd); } I want to unit test this
Continue readingAngular 10: Unit Testing with a HttpInterceptor that modifies the response not getting an HttpResponse
Issue If searched around SO for answers and so far, everything I’ve tried produces the same missing information. This is running Angular 10 with the latest version of Karma/Jasmine. Essentially, I have an HTTP Interceptor that is looking at the
Continue readingUnit test Angular Material Dialog – How to include MAT_DIALOG_DATA
Issue I am trying to unit test this material dialog to test if the template is rendering the right injected object. The component works fine when used properly Component – The Dialog export class ConfirmationDialogComponent { constructor(@Inject(MAT_DIALOG_DATA) private dialogModel: ConfirmationDialogModel)
Continue readingUnit test Angular Material Dialog – How to include MAT_DIALOG_DATA
Issue I am trying to unit test this material dialog to test if the template is rendering the right injected object. The component works fine when used properly Component – The Dialog export class ConfirmationDialogComponent { constructor(@Inject(MAT_DIALOG_DATA) private dialogModel: ConfirmationDialogModel)
Continue readingUnit test Angular Material Dialog – How to include MAT_DIALOG_DATA
Issue I am trying to unit test this material dialog to test if the template is rendering the right injected object. The component works fine when used properly Component – The Dialog export class ConfirmationDialogComponent { constructor(@Inject(MAT_DIALOG_DATA) private dialogModel: ConfirmationDialogModel)
Continue readingAngular Unit Test – How to inject dependencies to TestBed by using useValue in the TestBed provider
Issue The service I want to test has the following constructor: constructor(@Inject(‘enviroment’) environment) { this.initConfig(environment); } The environment is provided in app.module under providers by: { provide: ‘environment’, useValue: environment } So I configured the TestBed as follows: beforeEach(() =>
Continue readingAngular component test error: TypeError Cannot read property 'subscribe' of undefined
Issue I have a simple unit test that is done using karma/jasmine on an Angular 6 component. From the pluralsight course and documentation I have gathered it appears I am mocking my service correctly that my component requires, but when
Continue readingAngular component test error: TypeError Cannot read property 'subscribe' of undefined
Issue I have a simple unit test that is done using karma/jasmine on an Angular 6 component. From the pluralsight course and documentation I have gathered it appears I am mocking my service correctly that my component requires, but when
Continue readingUnit testing angular 11 service stub problem
Issue I’m trying to run unit test of my component. component.ts: async ngOnInit(): Promise<void> { await this.dataProviderService.getCurrencyCodesList().then(data => { this.currencyList = data; }); this.currencyList.sort((a, b) => { return a.code > b.code ? 1 : -1; }); // … } Service
Continue readingAngular Unit Testing – How to trigger another emit from an injected service?
Issue I have a component that does the following: In the constructor, it takes the query parameters and parses them into the given quarter and year In ngOnInit, it subscribes to a service that returns a list of quarters and
Continue readingProperty recognized as undefined in spec file even though it exist in the component. Unit Test in Angular with Karma – Jasmine
Issue I have the following method in a component in Angular but when I wrote the unit test for it, it fails, does not recognize properties that actually exists in the component; this is my method makeUrl(): string { const
Continue readingHow to unit test a nested if condition in with Karma-Jasmine in Angular?
Issue I have a function and I have a coverage of 75% with unit tests, however, I’d like to have a 100% of coverage of unit tests. This is the function: calculateRatingSummary(): void { if (this.averageRating > 0) { this.avgRatings
Continue readingAngular ngneat spectator service testing
Issue I am having trouble testing a service injected into an Angular component. Here is an example scenario I am facing. Let’s say I have SampleComponent that has SampleService injected. I want to test whether running handleAction() in SampleComponent calls
Continue readingAngular how to test component methods?
Issue I’m new to Angular and i’m trying to learn how to write tests. I don’t understand how to mock and test methods from components. My HTML is the following: (You have a table with all your certificates. By using
Continue readingAngular how to test service methods?
Issue I’m trying to learn how to write tests. I don’t understand how to mock and test methods from services. My current service file is the following: import {Injectable} from ‘@angular/core’; import {HttpClient, HttpErrorResponse} from ‘@angular/common/http’; import {Observable, throwError} from
Continue readingHow to run unit test case for toast message in angular service?
Issue I am working with an app based on Angular 12. I have service called notification service which handles toast messages from ngx-toastr library. This is how that service looks like: export class NotificationService { constructor(private toastr: ToastrService) {} showSuccess(message:
Continue readingAsyncTestZoneSpec is needed for the async – Angular
Issue The application was built on Angular v4 and was gradually updated with every release up until now. Currently we’re on Angular v7 and finally the CEO has agreed to write unit test while it wasn’t the case before. I
Continue readingHow to easily mock a service HTTP request with Jasmine (Angular)?
Issue Why wont this spy work? I am creating an instance of the prescriptionService and spying on the fetchClientPrescriptions method, but when I check to see if its been called, I get an error. Yet the first spy for getClientPrescriptions
Continue readingError: NG0302: The pipe 'myFilter' could not be found! when running ng test
Issue In my Angular project (v12) I use various custom pipes in different components. Everything is declared in app.modules.ts, however running ng test throws Error: NG0302: The pipe ‘myFilter’ could not be found! only for some (most recently created/used) pipes/components.
Continue readingHow to mock formControl value getTime() in unit tests
Issue I am trying to unit test a formControl’s getTime(). I am getting an error .getTime is not a function. A snippet of the component file looks like: import {FormControl} from @angular/forms; @component({ selector: ‘lorem-ipsum’, templateUrl: ‘./lorem-ipsum.html’ }) export class
Continue readingAngular2 unit test with @Input()
Issue I’ve got a component that uses the @Input() annotation on an instance variable and I’m trying to write my unit test for the openProductPage() method, but I’m a little lost at how I setup my unit test. I could
Continue readingHow can I test elements wrapped in an ng-container exist for Angular 6 with Jasmine?
Issue I am trying to write a unit test to see whether or not elements wrapped in an <ng-container> exist, but my tests fails because it seems the elements are created any way. My code is: HTML <ng-container *ngIf=”router.url ===
Continue readingTesting and anchor tag click inside a ng-container embbeded in a ng-switch
Issue I´m really new about testing in angular and I, couldn´t have found a solution for this problematic. Im trying to do a test over a method that is called once an anchor tag is clicked. This anchor tag is
Continue readingUnit Testing AngularJS and PouchDB Service
Issue I am attempting to unit test my individual Angular factories but am having a hard time trying to correctly mock and inject the PouchDB object. My factory code is currently as follows: factory(‘Track’, [function() { var db = new
Continue readingCreate unit tests where each test has its specific test data and test mocks
Issue I have this test structure and it is working but It does not cover my requirements when I put more tests in this unit test .js file , but all related tests should go there. WORKING: ‘use strict’; describe(‘lessonplannerFactory
Continue readingAngularJS Mock Self Executing Controller
Issue How do I prevent an angular controller with a self instantiating function from executing for tests? (I have used a contrived example to illustrate my issue) I have a controller that executes some code on startup (in my case
Continue readingHow do I mock $window injected manually in provider private function?
Issue I have the following provider: angular.module(‘MyApp’).provider(‘MyDevice’, function () { var ngInjector = angular.injector([‘ng’]), $window = ngInjector.get(‘$window’); function isMobileDevice () { return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/) .test($window.navigator.userAgent || $window.navigator.vendor || $window.opera); } this.$get = function () { return { isDesktop: function ()
Continue readingHow to Jasmine test code within angular module run block
Issue I would like to Jasmine test that Welcome.go has been called. Welcome is an angular service. angular.module(‘welcome’,[]) .run(function(Welcome) { Welcome.go(); }); This is my test so far: describe(‘module: welcome’, function () { beforeEach(module(‘welcome’)); var Welcome; beforeEach(inject(function(_Welcome_) { Welcome =
Continue readingAngular-mocks error instantiating $rootScope
Issue I have a very simple Mocha test (a copy of code that I have seen dozens of times) When I run it, angular mocks appears to successfully load the injected resources and all their dependencies and successfully makes it
Continue readingAngular-mocks error instantiating $rootScope
Issue I have a very simple Mocha test (a copy of code that I have seen dozens of times) When I run it, angular mocks appears to successfully load the injected resources and all their dependencies and successfully makes it
Continue readingAngular-mocks $injector doesn't return service, no $get method
Issue I am attempting to do my best at bdd with Karma and Mocha. I have created this shell of a service to try to get things going (generated from TypeScript) I have created the following test I put a
Continue readingAngular-mocks $injector doesn't return service, no $get method
Issue I am attempting to do my best at bdd with Karma and Mocha. I have created this shell of a service to try to get things going (generated from TypeScript) I have created the following test I put a
Continue readingHow do I test a decorator which is a wrapper around $timeout?
Issue I have the following decorator which wraps around the original $timeout from within $rootScope. When used inside controllers, it will help by canceling the $timeout promise when the scope is destroyed. angular.module(‘MyApp’).config([‘$provide’, function ($provide) { $provide.decorator(‘$rootScope’, [‘$delegate’, function ($delegate)
Continue readingTesting Initialization of AngularJS Service with Mocks
Issue I am trying to test the way an angular service responds to the values it gets from another service when it is initialized, and I’m having trouble finding a non-clunky way of doing it… much less one that works.
Continue readingngMock injecting $scope local into controller
Issue This is a continuation of another question I asked that was successfully answered. I’m learning how to unit test AngularJS applications with Karma, Jasmine, and ngMock. Here’s the code I have a question about: describe(‘myController function’, function() { describe(‘myController’,
Continue readingAngularJS Unit Testing Controller w/ service dependency in Jasmine
Issue I’m brand new to testing, and I’ve been trying to find the best strategy for unit testing an AngularJS controller with a service dependency. Here’s the source code: app.service(“StringService”, function() { this.addExcitement = function (str) { return str +
Continue readingJasmine and angular mocks : mocking a service that handles local storage
Issue I have one service called wd$cache, that is basically a wrapper for localStorage.setItem and get.item. Now I’m trying to test a controller that uses that service to achieve a certain result. The main problem is that I have an
Continue readingAngularJS Testing and $http
Issue So Im trying to figure out how to write unit tests for my angular controller. I am using karma as my runner. I was able to write 1 successful test but every time I try to write another test
Continue readingJasmine spyOn on function and returned object
Issue I’m using MeteorJS with angular and want to test controller. My controller use $reactive(this).attach($scope). I need to check, if this method was called. I create something like that for spy: var $reactive = function(ctrl) { return { attach:function(scope) {}
Continue readingHow to unit test (using Jasmine) a function in a controller which calls a factory service which returns a promise
Issue In the below SampleController, how do I unit test that postAttributes function calls sampleService.updateMethod. I’m having trouble since the updateMethod returns promise. angular.module(‘sampleModule’) .controller(‘SampleController’, SampleController); SampleController.$inject =[‘sampleService’]; function SampleController(sampleService){ this.postAttributes = function() { sampleService.updateMethod(number,attributes) .then(function(response){ //do something on successful
Continue readingWhat is the difference between calling _$controller_ instead of _$injector_.get('$controller')?
Issue beforeEach(inject(function (_$controller_, _$injector_) { ctrl = _$controller_(…) // 1 ctrl = _$injector_.get(‘$controller’)(…) // 2 })); What are the differences and which way is preferred? Solution Declaring _$controller_ in the parameters of the function passed to inject() makes the framework
Continue readingUnit Testing $routeParams in directive
Issue I have a directive that accesses the $routeParams of the page as such: myApp.directive(“myList”, function ($routeParams) { return { restrict: ‘E’, templateUrl: ‘tabs/my-list.html’, link: function (scope) { scope.year = $routeParams.year; } }; }); The directive works as expected and
Continue readingangular unit test $httpBackend got Unexpected request
Issue Here is my code: export class httpService { constructor($q, $http){ this.$q = $q; this.$http = $http; } static getError(response) { if (response.data && response.data.messages) { return response.data.messages; } else { return [“Sorry, there is an internal issue…”]; } }
Continue readingUnable to inject controller to Karma test
Issue I have spent hours trying to set up unit testing on an existing angularjs code base. I believe I have pinned the issue down to a single oddity in our code compared to the suggested implementation from angular’s docs.
Continue readingHow to test $scope in Jasmine test?
Issue I trying to write unit tests for Angularjs with Jasmine. Here is my controller: function HomeController($scope, fav, news, materials) { console.log(‘home controller’); $scope.testMe = true; } module.controller(‘HomeController’, HomeController); And tests describe(‘Home controller tests’, function() { var $rootScope, $scope, controller;
Continue readingUnit test controller
Issue I make an ionic app and it finish but when i start to add tests to it I face a problem with $resources ,in this case I have this Controller : .controller(‘newAccountCtrl’, function($scope, $window, $rootScope, API, $ionicPopup, $state) {
Continue readingHow to use ngMock to inject $controller
Issue I’m trying to learn unit testing for Angular using Karma, Jasmine, and ngMock. There are at least 2 places in the Angular docs that show how to write unit tests for a controller, and I just have a couple
Continue readingJasmine test error on Jenkins Build Server with angular-mocks?
Issue I’m unit testing a angular directive with Angular and Jasmine. Mocking the http backend works fine and all tests working fine locally. But on the build server i get: Error: Unexpected request: GET app/auth/views/login.html No more request expected (line
Continue readingAngular Mock Inject throws error without message using Karma and Jasmine
Issue Using the angular.mock.inject(…) function when trying to unit test an Angular (Ionic) 1 application throws the following error. The strange thing is that there is no specific error message, making particularly hard to debug. No matter what I try,
Continue readingUnit test $mdDialog angular material
Issue I called one $mdDialog inside a function. I want to unit-test $mdDialog ok and cancel cases. The below is my controller code (app.controller.js). (function () { ‘use strict’; app.controller(‘AppCtrl’, AppCtrl); AppCtrl.$inject = [‘$scope’, ‘$mdDialog’]; function AppCtrl($scope, $mdDialog) { $scope.saveEntry
Continue readingHow can I unit test the result of a ui-bootsrap $uibModal instance?
Issue I have a controller that calls $uibModal.open to pop a ui-bootstrap modal. The controller looks like this: (function () { ‘use strict’; angular .module(‘app’) .controller(‘MyCtrl’, myCtrl); function myCtrl($uibModal) { var vm = this; vm.showModal = showModal; vm.results = [];
Continue readingCircular dependencies on angular modules using typescript
Issue I’m facing this issue where i have 2 angular 1.5 modules that depend on each other, which is fine by angularjs, but when i import them using typescript & webpack, i get circular typescript-module dependencies and the modules are
Continue readingUse scope attribute of directive as class name in ngClass
Issue I want to use a scope attribute of a directive as the class name in ngClass someModule.directive(“someDirective”, function () { return { restrict: “A”, scope: { styleClass: ‘@’, }, replace: true, template: “<li ng-class='{‘{{styleClass}}:true’}’ />” } } I’ve tried
Continue readingHow to Mock only specific method in Golang
Issue I am fairly new to golang and I am struggling with a simple task. I have the following class in golang type struct A { } func (s *A) GetFirst() { s.getSecond() } func (s *A) getSecond() { //
Continue readingCan I write my own version of go's http client.Do() function for my test cases?
Issue I have a file, called user-service.go and the corresponding test file, called user-service_test.go. As I try to get complete code coverage, I am struggling to get some of the error conditions to actually happen. Here is the function: GetOrCreateByAccessToken()
Continue readingCan I write my own version of go's http client.Do() function for my test cases?
Issue I have a file, called user-service.go and the corresponding test file, called user-service_test.go. As I try to get complete code coverage, I am struggling to get some of the error conditions to actually happen. Here is the function: GetOrCreateByAccessToken()
Continue readingI modified gtest/gmock so it is really easy to mock non-virtual functions
Issue You know sometimes when something does not work and you want a quick fix you get stupid ideas … I mean really stupid ideas. But somehow they work. So to be able to mock non-virtual functions I deleted every
Continue readingHow to test Angular 1.6 component with injected service?
Issue I want to test my Angular component which is syntactically based on John Papa’s styleguide: ‘use strict’; angular.module(‘MyModule’) .component(‘MyCmpnt’, MyCmpnt()) .controller(‘MyCtrl’, MyCtrl); function MyCmpnt() { return { restrict: ‘E’, templateUrl: ‘myPath/myTemplate.html’, bindings: { foo: ‘=’, bar: ‘<‘ }, controller:
Continue readingAngularJS/Karma/Jasmine – Service call not returning value
Issue I’m attempting to make a call to a Github API using a service injected into a component – and yes, I am using AngularJS 1.5.3. In the unit test, I am not receiving back a value (the function does
Continue readingUnit testing ngComponentRouter – Angular 1.5.x
Issue I am trying to build basic unit tests for an Angular 1.5 with the purpose of A) practicing unit testing, and B) familiarizing myself with component-based development in Angular 1.5.x. I’m trying to unit test a simple component, but
Continue readingI have a problem with testing adding user with password encoder
Issue I have a problem when testing a method with using passwordencoder: Cannot invoke "org.springframework.security.crypto.password.PasswordEncoder.encode(java.lang.CharSequence)" because the return value of "com.store.restAPI.user.UserConfig.passwordEncoder()" is null` Thats my test class method: @ExtendWith(MockitoExtension.class) class UserServiceTest { private UserService underTest; @Mock private UserRepository userRepository; @Mock
Continue readingRe-direct requests to SideEffect Utility Classes
Issue for a spring boot application that needs to be tested below is my query. @CustomLog @RestController @RequestMapping("/my_path") public class MyController { @GetMapping(path = "**", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<JsonNode> fetchData(HttpServletRequest request){ … some code…..which also calls external apis….. }
Continue readingapollo-angular throws Error when using a mockError on Jasmine/Karma testing
Issue I’ve tested errors on queries/mutations like these for years, but just now, I got one error I can’t seem to figure it out. When I call this test, Apollo is throwing an error for the errorMock I’ve made. Has
Continue readingHow to unit test angularjs route's resolve with karma and mocha+chai?
Issue I am working on an app where I need to resolve promises in the router (ngRoute). The problem is that I am not sure how to write the unit tests for this, I am using karma with mocha and
Continue readingWhy do Angular unit tests load $route?
Issue After updating to Angular 1.5.3 (from 1.4.9) all my unit tests have started failing, where they worked before. The error is as follows: Error: [$injector:unpr] Unknown provider: AuthenticationHttpInterceptorProvider <- AuthenticationHttpInterceptor <- $http <- $templateRequest <- $route It is expected
Continue readingHow to write unit test to Restangular with Jasmine?
Issue I know how to write test to GET methods, but what with other methods? PUT, PATCH, DELETE? This is for example my service method to remove user: removeOne: function(user) { var deferred; console.log(user); deferred = $q.defer(); if (_.isUndefined(user.id) ||
Continue readingcan i set a base url for expect()
Issue My restangular call has a baseUrl set in a config file to http://localhost:3000/. So a call like Restangular.all(“awards”).customPOST(award) Calls at baseUrl+”awards” Now when I write a test for this, i have to write: httpBackend.expectPOST(“http://localhost:3000/awards”) But later if this baseUrl
Continue readingAngular httpBackend crashing browser
Issue When using Jasmine and Angular (1.4.7) with Restangular (1.4.0), httpBackend and angular-mocks (1.4.7), Chrome and PhantomJS both crash when encountering the following line: httpBackend.whenGET(‘/something’).respond(200); If I get rid of it entirely, as below, I get the following error: //httpBackend.whenGET(‘/something’).respond(200);
Continue readingMock Activated Route With Params in Angular
Issue Question How to mock ActivatedRoutes in my unit tests? Service: constructor( private route: ActivatedRoute, private knowledgeModelService: KnowledgeModelService ) { route.params.pipe(map(p => p.modelId)).subscribe((modelId) => { this.modelId = modelId; }); } My unit test: With mock class class ActivatedRouteMock { //
Continue readingHow to mock ActivatedRoute in Angular without using TestBed
Issue The question is pretty simple. I have never really liked how the original testing works in Angular (the TestBed part), so I have always done it the classic way: mocking with ts-mockito. No TestBed, no configuration needed, zero confusion.
Continue readingli tag with conditional always not visble in angular test with jest
Issue Good day developers . Im trying to test the show hide behaviour of a <li/> tag according to a specific variable. For that this <li/> tag has an *ngIf bound: <ul class="item" js-selector="tab-list"> <li class="item" js-selector="tab" *ngIf="isTabEnabled" … >
Continue reading