Pact consumer tests in angular and HttpIntercepter - karma-runner

Our application uses HttpInterceptor to convert JSON properties from camel-case to snake-case.
I configure pact in karma.conf.js and set pact proxy there.
For my test I use TestBed:
TestBed.configureTestingModule({
imports: [
HttpClientModule
],
providers: [
EmployeeService,
{ provide: SERVER_URLS, useValue: TokenPactMock.SERVER_URLS() },
{ provide: HTTP_RETRY_ATTEMPTS, useValue: TokenMock.HTTP_RETRY_ATTEMPTS() }
],
});
and this is my test:
const employeeService: EmployeeService = TestBed.get(EmployeeServiceService);
employeeService.addEmployee(employee).subscribe(response => {
expect(response.status).toEqual(201);
expect(response.body).toEqual(employee);
done();
}, error => {
done.fail(error);
});
This test runs successfully and pact file is generated. But HttpInterceptor was not trigger and in PACT file I have camel-case properties instead of snake-case.
Does anybody know how to use PACT with HttpInterceptor?

We have found the answer. It was our misunderstanding of difference between HttpClientModule and HttpClientTestingModule.
In HttpClientModule we must explicitly define our listeners:
TestBed.configureTestingModule({
imports: [
HttpClientModule
],
providers: [
EmployeeService,
{ provide: SERVER_URLS, useValue: TokenPactMock.SERVER_URLS() },
{ provide: HTTP_INTERCEPTORS, useClass: HttpNamingInterceptor, multi: true },
{ provide: HTTP_RETRY_ATTEMPTS, useValue: TokenMock.HTTP_RETRY_ATTEMPTS() }
],
});

Related

How inject service in component

I have a component and service, I try to inject service (ListUserService) in component.
I import the service, I request it and I get an error, when I delete the service it works well, what is the error?
import { Component, OnInit } from '#angular/core';
import {ListUserService} from './list-user.service';
#Component({
selector: 'app-list-user',
templateUrl: './list-user.component.html',
styleUrls: ['./list-user.component.scss'],
providers: [ListUserService]
})
export class ListUserComponent implements OnInit {
constructor(private listUserService: ListUserService) {
console.log(this.listUserService);
}
}
and this is the service:
import {Injectable} from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ListUserService {
constructor(public http: HttpClient) {
this.http.get(`http://localhost:8080/user/getUsers/`)
.subscribe(response => {
console.log(response);
});
}
}
this is the error:
ERROR
Error: StaticInjectorError(AppModule)[ListUserService -> HttpClient]:
StaticInjectorError(Platform: core)[ListUserService -> HttpClient]:
NullInjectorError: No provider for HttpClient!
this is the file app.module.ts
import {HttpClient} from '#angular/common/http';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {ListUserComponent} from './list-user/list-user.component';
import {ListUserService} from './list-user/list-user.service';
#NgModule({
declarations: [AppComponent, ListUserComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
HttpClient,
StatusBar,
SplashScreen,
ListUserService,
{provide: RouteReuseStrategy, useClass: IonicRouteStrategy}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
You have failed to add HttpClientModule in imports of app.module.ts
import { ListUserComponent } from './list-user/list-user.component';
import { ListUserService } from './list-user/list-user.service';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [AppComponent, ListUserComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule],
providers: [
StatusBar,
SplashScreen,
ListUserService,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Add your Service to the providers: [ListUserService] in your app.module.ts
https://angular.io/guide/ngmodules
EDIT: HttpClient must be added to providers: [ListUserService, HttpClient] aswell as import {HttpClient} from '#angular/common/http';

Adding File and FilePath inside provider in App module throws error in Ionic 3

After installing all needed dependencies and importing them in App Module it throws error for File and File path. Like it can't be included inside providers.
import { Camera } from '#ionic-native/camera';
import { MyApp } from './app.component';
import { File } from '#ionic-native/file';
import { Transfer } from '#ionic-native/transfer';
import { FilePath } from '#ionic-native/file-path';
#NgModule({
declarations: [MyApp],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot(),
EmojiPickerModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [MyApp],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler },
AuthProvider,
TokenProvider,
MessageProvider,
File,
Transfer,
Camera,
FilePath,
PostProvider,
UsersProvider,
]
})
export class AppModule {}
Why it doesn't allow to implement these 2 ones in the providers section? How can this be fixed? We are using Ionic 3

Can't resolve all parameters for Deploy: (?, ?)

When I am trying to add ionic deploy service on an application I get the Following Error:
if you add Deploy to providers
please remove it and app will run again
You shouldn't add Deploy as a provider. The right way for using Deploy with Ionic is defined on this webpage: https://docs.ionic.io/setup.html#installation
// app.module.ts
import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'APP_ID'
}
};
#NgModule({
declarations: [ ... ],
imports: [
IonicModule.forRoot(MyApp),
CloudModule.forRoot(cloudSettings)
],
bootstrap: [IonicApp],
entryComponents: [ ... ],
providers: [ ... ]
})
export class AppModule {}

Navigating to a Page that has a component not working in Ionic Framework: 3.0.1

I have added the Page(HomePage) that has a component in it in entryComponents but still getting a error as "Error: Uncaught (in promise): Error: Component HomePage is not part of any NgModule or the module has not been imported into your module."
Code Block--
login.module.ts----
#NgModule({
declarations: [
LoginPage,
],
imports: [
IonicPageModule.forChild(LoginPage),
],
exports: [
LoginPage
],
entryComponents:[HomePage]// Added here
})
export class LoginModule {}
-----
login.ts----------------
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
createUserId(){
this.myProvider.createUserId(this.value,data=>{
if(data=="success")
{
this.check_response="UserID created"
this.navCtrl.push(HomePage)//-----Getting an error here
}
else
this.check_response="Failure"
})
//console.log("submit")
}
}
homepage.module.ts-----------
#NgModule({
declarations: [
HomePage
],
imports: [
IonicPageModule.forChild(HomePage),
AddExpenseModule
],
exports: [
HomePage
]
})
export class HomePageModule {}
You need to also include HomePage in the declarations array of ngModule. All app components, directives, etc need to do in the declarations array. A good detailed explanation is available here: https://www.joshmorony.com/an-introduction-to-ngmodule-for-ionic-2/

karma-browserify throws error when trying to load modules shimmed with browserify-shim

I know there were similar questions but none of them solved my problem.
When I run karma test it throws the following error, every time it tries to load a module, that was shimmed with browserify-shim:
TypeError: 'undefined' is not an object (evaluating 'module.exports = ex')
at /tmp/8ff1e03f7ba1f9c70ee4192510d267a2.browserify:3855:0 <- lib/underscore/underscore.js:1421:0
My karma.conf.js is the following:
module.exports = function(karma) {
karma.set({
frameworks: [ 'jasmine', 'browserify' ],
files: [
'test/spec/**/*Spec.js'
],
reporters: [ 'dots' ],
preprocessors: {
'test/spec/**/*Spec.js': [ 'browserify' ]
},
browsers: [ 'PhantomJS' ],
logLevel: 'LOG_DEBUG',
singleRun: true,
autoWatch: false,
// browserify configuration
browserify: {
debug: true,
transform: [ 'reactify', 'browserify-shim' ]
}
});
};
And here is the relevant part of my package.json file:
...
"browser": {
"underscore": "./lib/underscore/underscore.js",
"jquery": "./lib/jquery/dist/jquery.js",
"typeahead": "./lib/bootstrap3-typeahead/bootstrap3-typeahead.js",
"bootstrap": "./lib/bootstrap/dist/js/bootstrap.js",
"q": "./lib/q/q.js"
},
"browserify-shim": {
"underscore": "_",
"jquery": "jQuery",
"typeahead": {
"depends": [
"jquery"
]
}
},
"browserify": {
"transform": [
"browserify-shim"
]
},
....
Any idea what can caus the problem?
I had the same problem and have resolved it by removing the browserify-shim transform from karma configuration file, since it is already declared as a transform on package.json file.
Hope that helps.