I'm using pino-logger in my NestJS project to log the activities in my application, and I'm logging the object along with ReqId so I can trace the whole activity inside one request. I'd like to use the same "ReqId" in another place as well, but I'm unsure of how to move it outside of the module, so for that, I'm thinking to save that generated ReqId into the CacheManager but not sure how to inject CacheManager class inside genReqId function. Please look over the code below.
app.module.ts
#Module({
imports: [
LoggerModule.forRoot({
pinoHttp: {
genReqId: (req: any) => {
// I'm thinking to use CacheManager here but I'm not sure how to inject CacheManager class here
return req.headers.req_id || uuid(); // from here it generate the request ID and I want to export this ID and use in side an another class
},
base: undefined,
quietReqLogger: true,
timestamp: false,
},
}),
],
})
export class AppModule {}
you need To create sharable service and import it Imports
#Injectable()
export class RequestIdService {
private reqId: string;
setRequestId(reqId: string) {
this.reqId = reqId;
}
getRequestId() {
return this.reqId;
}
}
than import it to logger module
imports: [
LoggerModule.forRoot({
pinoHttp: {
genReqId: (req: any) => {
this.requestIdService.setRequestId(req.headers.req_id || uuid());
return this.requestIdService.getRequestId();
},
base: undefined,
quietReqLogger: true,
timestamp: false,
},
}),
],
providers: [RequestIdService],
```
use that service by
import { RequestIdService } from './request-id.service';
this.requestIdService.getRequestId()
I'm stuck on this again and although this thread (MockService still causes error: Cannot read property 'subscribe' of undefined) is exactly about the same thing it still doesn't resolve my problem.
I do have a component which calls a simple function on ngOnInit:
ngOnInit() {
this.getModules();
}
getModules() {
this.configService.getModulesToDisplay().subscribe(modules => {
this.modulesToDisplay = modules;
}
);
}
I want to test two things:
Is getModules called on ngOnInit
and
Is this.modulesToDisplayed reassigned when it gets some result
So I mocked my service but the first test still fails with the TypeError 'Cannot read property 'subscribe' of undefined'.
I moved my mocked Service to all different areas since I do guess the mock isn't available when the test starts to build the component. But I still couldn't make it out. My Test looks like:
describe('NavigationComponent', () => {
let component: NavigationComponent;
let fixture: ComponentFixture<NavigationComponent>;
let configServiceMock: any;
beforeEach(async(() => {
configServiceMock = jasmine.createSpyObj('ConfigService', ['getModulesToDisplay']);
configServiceMock.getModulesToDisplay.and.returnValue( of(['module1', 'module2']) );
TestBed.configureTestingModule({
declarations: [
NavigationComponent
],
imports: [
RouterTestingModule,
HttpClientTestingModule
],
providers: [
{ provide: ConfigService, useValue: configServiceMock },
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
}).compileComponents();
beforeEach(() => {
// configServiceMock.getModulesToDisplay.and.returnValue( of(['module1', 'module2']) );
fixture = TestBed.createComponent(NavigationComponent);
component = fixture.componentInstance;
});
}));
I removed fixture.detectChanges() to have full control over when ngOnInit should be called and so my tests look like:
it('should call getModulesToDisplay one time on ngOninit()', () => {
const spyGetModules = spyOn(component, 'getModules');
component.ngOnInit();
expect(spyGetModules).toHaveBeenCalledTimes(1);
});
The first test fails with the Cannot read subscribe error. But the second one passes with the correct mockvalue being used.
it('should assign result to modulesToDisplay', () => {
component.getModules();
expect(component.modulesToDisplay.length).toBeGreaterThan(0);
});
Any hints on what am I still missing are highly appreciated!
Rather than writing jasmine spy in each spec file, create a reusable Mock file
export class MockConfigService{
getModulesToDisplay(){
return of({
// whatever module object structure is
})
}
}
and in it block:
it('should call getModulesToDisplay one time on ngOninit()', () => {
spyOn(component, 'getModules').and.callThrough();
component.ngOnInit();
expect(component.getModules).toHaveBeenCalledTimes(1);
});
My company uses Keycloak for authentication connected with LDAP and returning a user object filled with corporative data.
Yet in this period we are all working from home and in my daily work having to authenticate in my corporative server every time I reload the app, has proven to be an expensive overhead. Especially with intermittent internet connections.
How can I fake the Keycloak call and make keycloak.protect() work as it has succeeded?
I can install a Keyclock server in my machine, but I'd rather not do that because it would be another server running in it besides, vagrant VM, Postgres server, be server, and all the other things I leave open.
It would be best to make a mock call and return a fixed hard-coded object.
My project's app-init.ts is this:
import { KeycloakService } from 'keycloak-angular';
import { KeycloakUser } from './shared/models/keycloakUser';
<...>
export function initializer(
keycloak: KeycloakService,
<...>
): () => Promise<any> {
return (): Promise<any> => {
return new Promise(async (res, rej) => {
<...>
await keycloak.init({
config: environment.keycloakConfig,
initOptions: {
onLoad: 'login-required',
// onLoad: 'check-sso',
checkLoginIframe: false
},
bearerExcludedUrls: [],
loadUserProfileAtStartUp: false
}).then((authenticated: boolean) => {
if (!authenticated) return;
keycloak.getKeycloakInstance()
.loadUserInfo()
.success(async (user: KeycloakUser) => {
// ...
// load authenticated user data
// ...
})
}).catch((err: any) => rej(err));
res();
});
};
I just need one fixed logged user. But it has to return some fixed customized data with it. Something like this:
{ username: '111111111-11', name: 'Whatever Something de Paula',
email: 'whatever#gmail.com', department: 'sales', employee_number: 7777777 }
EDIT
I tried to look at the idea of #BojanKogoj but AFAIU from Angular Interceptor page and other examples and tutorials, it has to be injected in a component. Keycloak initialization is called on app initialization, not in a component. Also Keycloak's return is not the direct return of init() method. It passes through other objects in the .getKeycloakInstance().loadUserInfo().success() sequence.
Or maybe it's just me that didn't fully understand it. If anyone can come with an example of an interceptor that can intercept the call and return the correct result, that could be a possibility.
Edit2
Just to complement that what I need is for the whole keycloak's system to work. Please notice that the (user: KeycloakUser) => { function is passed to success method of keycloak's internal system. As I said above, routes have a keycloak.protect() that must work. So it's not just a simple case of returning a promise with a user. The whole .getKeycloakInstance().loadUserInfo().success() chain has to be mocked. Or at least that's how I understand it.
I included an answer with the solution I made based on #yurzui's answer
Will wait a couple of days to award the bounty to see if someone can came up with an even better solution (which I doubt).
You can leverage Angular environment(or even process.env) variable to switch between real and mock implementations.
Here is a simple example of how to do that:
app-init.ts
...
import { environment } from '../environments/environment';
export function initializer(
keycloak: KeycloakService
): () => Promise<any> {
function authenticate() {
return keycloak
.init({
config: {} as any,
initOptions: {onLoad: 'login-required', checkLoginIframe: false},
bearerExcludedUrls: [],
loadUserProfileAtStartUp: false
})
.then(authenticated => {
return authenticated ? keycloak.getKeycloakInstance().loadUserInfo() : Promise.reject();
});
}
// we use 'any' here so you don't have to define keyCloakUser in each environment
const { keyCloakUser } = environment as any;
return () => {
return (keyCloakUser ? Promise.resolve(keyCloakUser) : authenticate()).then(user => {
// ...
// do whatever you want with user
// ...
});
};
}
environment.ts
export const environment = {
production: false,
keyCloakUser: {
username: '111111111-11',
name: 'Whatever Something de Paula',
email: 'whatever#gmail.com',
}
};
environment.prod.ts
export const environment = {
production: true,
};
Update
If you want to mock KeycloakService on client side then you can tell Angular dependency injection to handle that:
app.module.ts
import { environment } from '../environments/environment';
import { KeycloakService, KeycloakAngularModule } from 'keycloak-angular';
import { MockedKeycloakService } from './mocked-keycloak.service';
#NgModule({
...
imports: [
...
KeycloakAngularModule
],
providers: [
{
provide: KeycloakService,
useClass: environment.production ? KeycloakService : MockedKeycloakService
},
{
provide: APP_INITIALIZER,
useFactory: initializer,
multi: true,
deps: [KeycloakService]
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
mocked-keycloak.service.ts
import { Injectable} from '#angular/core';
import { KeycloakService } from 'keycloak-angular';
#Injectable()
class MockedKeycloakService extends KeycloakService {
init() {
return Promise.resolve(true);
}
getKeycloakInstance() {
return {
loadUserInfo: () => {
let callback;
Promise.resolve().then(() => {
callback({
userName: 'name'
});
});
return {
success: (fn) => callback = fn
};
}
} as any;
}
}
Although you explicitly state that you think that mocking is the best option, I suggest to reconsider it in favor of setting up local Keycloak instance using docker. It becomes easy when you provide a realm to bootstrap your environment. I've been using this approach with success for over 2 years of developing applications that work with Keycloak. This approach will let you "substitute calls to your corporate server" hence I post it here.
Assuming that you have docker & docker-compose installed, you'll need:
1. docker-compose.yaml
version: '3.7'
services:
keycloak:
image: jboss/keycloak:10.0.1
environment:
KEYCLOAK_USER: admin
KEYCLOAK_PASSWORD: admin
KEYCLOAK_IMPORT: /tmp/dev-realm.json
ports:
- 8080:8080
volumes:
- ./dev-realm.json:/tmp/dev-realm.json
2. dev-realm.json (exact content depend on required settings, this is the minimum that you've mentioned in your question)
{
"id": "dev",
"realm": "dev",
"enabled": true,
"clients": [
{
"clientId": "app",
"enabled": true,
"redirectUris": [
"*"
],
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"secret": "mysecret",
"publicClient": false,
"protocol": "openid-connect",
"fullScopeAllowed": false,
"protocolMappers": [
{
"name": "department",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"user.attribute": "department",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "department",
"userinfo.token.claim": "true"
}
},
{
"name": "employee_number",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"user.attribute": "employee_number",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "employee_number",
"userinfo.token.claim": "true"
}
}
]
}
],
"users": [
{
"username": "111111111-11",
"enabled": true,
"firstName": "Whatever Something de Paula",
"email": "whatever#gmail.com",
"credentials": [{
"type": "password",
"value": "demo"
}],
"attributes": {
"department": "sales",
"employee_number": 7777777
}
}
]
}
3. Create dedicated Angular environment that will use the "http://localhost:8080/auth" and realm "dev" for your local development
The advantages of this approach over mocking:
all OIDC and keycloak features are working. I admit that it depends if you need them but you are free to use realm/client roles, groups, 'real' OIDC flow with token refreshal. This gives you guarantee that your local setup will work also with corporate service
this setup can be stored in repository (contrary to manual setup of Keycloak server) and used both for working on web applications and backend services
By default, Keycloak uses a H2 in-memory database and needs about 600MB of RAM so I'd argue that it is a relatively low footprint.
Solution
I was able to mock Keycloak service using the method #yurzui suggested. I'll document it here as it may be useful for somebody.
Initially I had posted a solution where I conditionally exported the mock or real classes from the mock module. All worked well on dev mode, but when I tried to build the application for publishing in production server I got an error, so I had to return to the 2 class solution. I explain the problem in details this question .
This is the working code (so far).
Frontend:
With a little help from #kev's answer in this question and #yurzui (again :D) in this one, I created a MockKeycloakService class:
import { Injectable } from '#angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from '../../../environments/environment';
#Injectable({ providedIn: 'root' })
export default class MockKeycloakService {
init() {
console.log('[KEYCLOAK] Mocked Keycloak call');
return Promise.resolve(true);
}
getKeycloakInstance() {
return {
loadUserInfo: () => {
let callback : any;
Promise.resolve().then(() => {
callback({
username: '77363698953',
NOME: 'Nelson Teixeira',
FOTO: 'assets/usuarios/nelson.jpg',
LOTACAOCOMPLETA: 'DIOPE/SUPOP/OPSRL/OPSMC (local)',
});
});
return { success: fn=>callback = fn };
}
} as any;
}
login() {}
logout() {}
}
const KeycloakServiceImpl =
environment.production ? KeycloakService : MockKeycloakService
export { KeycloakServiceImpl, KeycloakService, MockKeycloakService };
then I substituted it in app.module:
<...>
import { KeycloakAngularModule } from 'keycloak-angular';
import { KeycloakServiceImpl } from 'src/app/shared/services/keycloak-mock.service';
import { initializer } from './app-init';
<...>
imports: [
KeycloakAngularModule,
<...>
],
providers: [
<...>,
{
provide: APP_INITIALIZER,
useFactory: initializer,
multi: true,
deps: [KeycloakServiceImpl, <...>]
},
<...>
],
bootstrap: [AppComponent]
})
export class AppModule { }
Then changed the type of keycloak service variable in app-init, that was the only change, but then I could remove KeycloackService import as it's being provided in app.module:
import { KeycloakUser } from './shared/models/keycloakUser';
<...>
export function initializer(
keycloakService: any,
<...>
): () => Promise<any> {
return (): Promise<any> => {
return new Promise(async (res, rej) => {
<...>
await keycloak.init({
config: environment.keycloakConfig,
initOptions: {
onLoad: 'login-required',
// onLoad: 'check-sso',
checkLoginIframe: false
},
bearerExcludedUrls: [],
loadUserProfileAtStartUp: false
}).then((authenticated: boolean) => {
if (!authenticated) return;
keycloak.getKeycloakInstance()
.loadUserInfo()
.success(async (user: KeycloakUser) => {
<...>
})
}).catch((err: any) => rej(err));
res();
});
};
But in the component I still have to check which environment I'm on and instance the class correctly:
<...>
import { MockKeycloakService } from '../../shared/services/keycloak.mock.service';
import { environment } from '../../../environments/environment';
<...>
export class MainComponent implements OnInit, OnDestroy {
<...>
keycloak: any;
constructor(
<...>
) {
this.keycloak = (environment.production) ? KeycloakServiceImpl : new KeycloakServiceImpl();
}
async doLogout() {
await this.keycloak.logout();
}
async doLogin() {
await this.keycloak.login();
}
<...>
}
Backend:
That was easier, again I created a KeycloakMock class:
import KeyCloack from 'keycloak-connect';
class KeycloakMock {
constructor(store, config) {
//ignore them
}
middleware() {
return (req, res, next) =>{
next();
}}
protect(req, res, next) {
return (req, res, next) =>{
next();
}}
}
const exportKeycloak =
(process.env.NODE_ENV == 'local') ? KeycloakMock : KeyCloack;
export default exportKeycloak;
Then I just substitued 'keycloak-connect' import on app.js by this class, and everythig worked fine. It connects to the real service if I set production = true and it mocks it with production = false.
Very cool solution. If anyone has anything to say on my implementation of #yurzui idea I'll like to hear from you.
Some notes:
I still couln't get rid of having to check the environment in the main-component class, as if I do this in the mock class module:
const KeycloakServiceImpl =
environment.production ? KeycloakService : new MockKeycloakService()
app.module doesn't work anymore. and if I do this in main-component:
constructor(
<...>
keycloakService: KeyclockServiceImpl;
) { }
The build fails with a "KeyclockServiceImpl refers to a value but is being used as a type here";
I had to export all classes or the build fails
export { KeycloakServiceImpl, KeycloakService, MockKeycloakService };
mockData.js
var userInfo = {
URLs: {
AppURL: "A"
},
EncryptedBPC: "B"
};
karma.config.js
config.set({
basePath: '',
files:['mockData.js' ],
.....
ComponentDetailsComponent:
.....some imports
import { ComponentDetailsService } from '../component-details.service';
declare var userInfo: any;
#Component({
.....more code
rfxFilter() {
return userInfo.URLs.AppURL;
}
}
Spec:
describe('ComponentDetailsComponent', () => {
let subject:any;
let fixture: ComponentFixture<ComponentDetailsComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ComponentDetailsComponent ],
providers: [{ provide: ComponentDetailsService, useClass:
ComponentDetailsServiceStub }],
});
fixture = TestBed.createComponent(ComponentDetailsComponent);
subject = fixture.componentInstance;
});
it('should return X', () => {
subject.userInfo = {
URLs: {
AppURL: "X"
},
EncryptedBPC: "Y"
};
let result = subject.rfxFilter();
expect(result).toBe("X");
});
});
Output:
ReferenceError: userInfo is not defined
I have made it work by creating a method inside the component which will return userInfo global variable.
getuserInfo():any{
return userInfo;
}
And mocking that method in spec:
let m = {
URLs: {
AppURL: "mockvalueAppURL",
},
EncryptedBPC: "mockEncryptedBPC",
};
let spy = spyOn(subject, 'getuserInfo').and.returnValue(m);
Is it not possible to mock such global variables without having to encapsulate it within methods and then mocking the method instead of variable? I would like to keep the application code untouched when written by somebody else.
You can't access any variables of any other files. You can't mock imports either. Your best friend is DI, as you can provide mock class in place of original for testing.
You will have to mock the service that provides the data, not having the data in a separate file. The only way would be to export JSON, or object and use the exported object.
TestBed.configureTestingModule({
imports: [
],
declarations: [
ComponentDetailsComponent,
],
providers: [
{
provide: RealService,
useExisting: StubService,
},
],
}).compileComponents();
And implement the stub as this.
class StubService implements Partial<RealService> {
getuserInfo() {
return { ...mockedData };
}
}
Note:
If you are dealing with mocking HTTP calls use HttpTestingController.
Using the process outlined here, I'm trying to inject Angular 1 services into an Angular 4 app. The app is bootstrapped in hybrid mode (and works as I have some Angular 4 components and services running).
Whenever I try to inject the Angular 1 service, I get Cannot read property 'get' of undefined.
upgraded-providers.ts:
import {LinksService} from "./+services/links/links";
export function linksServiceFactory(i: any) {
return i.get('bfLinksService'); // <--- Errors here!
}
export const linksServiceProvider = {
provide: LinksService,
useFactory: linksServiceFactory,
deps: ['$injector']
};
My Angular 4 service which is trying to use LinksService looks like:
#Injectable()
export class EntityService {
constructor (
private http: Http,
private links: LinksService
) {
}
get(id: string): Observable<OrgDetails> {
// Do something
}
}
And finally LinksService (the Angular 1 service, written in Typescript) looks like:
export class LinksService {
static $inject = ["$log", "$location", PROPERTIES_SERVICE];
private contentHost : string;
private thisAppHost : string;
constructor (private $log : ng.ILogService, private $location : ng.ILocationService, private props : IPropertiesService) {
this.init();
}
// Service functions elided
}
The bootstrap and module stuff:
#NgModule({
imports: [
BrowserModule,
HttpModule,
UpgradeModule,
],
declarations: [
AppComponent,
OrgSummaryComponent,
],
providers: [
EntityService,
linksServiceProvider
],
bootstrap: [
AppComponent,
],
})
export class AppModule {
ngDoBootstrap() {
// Does nothing by design.
// This is to facilitate "hybrid bootstrapping"
}
}
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, [AppModuleName], {strictDi: false});
});
The Angular 1 (legacy) stuff all works fine.
It seems like Angular cant find the $injector, but shouldn't that be there regardless?
Many thanks for any suggestions,
Jeff
Two days of my life I won't get back but...
Just found this:
https://github.com/angular/angular.io/issues/3317
Basically the documentation is wrong. By adding a constrcutor to the app module with the call to upgrade.bootstrap in it, everything works.
export class AppModule {
constructor(upgrade: UpgradeModule) {
upgrade.bootstrap(document.body, [AppModuleName], {strictDi: true});
}
// Does nothing by design.
// This is to facilitate "hybrid bootstrapping"
ngDoBootstrap() {}
}
platformBrowserDynamic().bootstrapModule(AppModule);
Thank you to those who responded.
Actually the better way to instantiate AngularJS is after:
platformBrowserDynamic().bootstrapModule(AppModule)
.then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, ['app'], { strictDi: false });
})
.catch(err => console.log(err));