Testing Error in Karma: Can't bind to 'cdkObserveContentDisabled' since it isn't a known property of 'label' - forms

Setting up basic testing with parent component using a child FORM component. Getting the following error,
Failed: Template parse errors:
Can't bind to 'cdkObserveContentDisabled' since it isn't a known property of 'label'. ("m-field-label-wrapper">][cdkObserveContentDisabled]="appearance != 'outline'" [id]="_labelId" [attr.for]="_control.id" [attr."): ng:///DynamicTestModule/MatFormField.html#0:930
Error: Template parse errors:
Can't bind to 'cdkObserveContentDisabled' since it isn't a known property of 'label'
component.spec.ts is
import { CreatepageComponent } from './createpage.component';
import { NavbarComponent } from '../common/navbar/navbar.component';
import { TitleComponent } from '../common/title/title.component';
import { MobileTitleComponent } from '../common/mobile-title/mobile-title.component';
import { FormComponent } from '../common/form/form.component';
import { FooterComponent } from '../common/footer/footer.component';
import { MapComponent } from '../common/map/map.component';
import { SvgComponent } from '../common/svg/svg.component';
import { SvgDefinitionsComponent } from '../common/svg/svg-definitions/svg-definitions.component';
import { LinkComponent } from '../common/link/link.component';
import { DropdownMenuComponent } from '../common/dropdown-menu/dropdown-menu.component';
import { RouterTestingModule } from '#angular/router/testing';
import { RouterModule } from '#angular/router';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { ValidationErrorsComponent } from '../common/form/validation-errors/validation-errors.component';
import {
MatError,
MatFormFieldModule,
MatInputModule,
MatFormField,
MatLabel,
} from '#angular/material';
import { ButtonComponent } from '../common/button/button.component';
describe('CreatepageComponent', () => {
let component: CreatepageComponent;
let fixture: ComponentFixture<CreatepageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
CreatepageComponent,
NavbarComponent,
TitleComponent,
MobileTitleComponent,
FormComponent,
FooterComponent,
SvgComponent,
SvgDefinitionsComponent,
LinkComponent,
DropdownMenuComponent,
ValidationErrorsComponent,
MatError,
MatFormField,
ButtonComponent,
MapComponent
],
providers: [
RouterModule,
ReactiveFormsModule,
FormsModule,
MatFormFieldModule,
MatInputModule,
MatLabel
],
imports: [FormsModule, ReactiveFormsModule, RouterTestingModule]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CreatepageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Expected: Karma passes all tests
Actual: Karma responds with errors in any component with the form as a child.

Just ran into this myself. It looks like you need to import ObserversModule from '#angular/cdk/observers' in your spec.ts file, and include it in the 'imports' section under the configureTestingModule function.
import {ObserversModule} from '#angular/cdk/observers'; <== HERE
---------------------------
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [ObserversModule] <== HERE
},)
.compileComponents();
}));
Seen here:
https://material.angular.io/cdk/observers/api

Related

Trouble with module import [ NEST JS ]

I'm trying to use a jwt.strategy.ts to protect my endpoints with jwt verification. Everything was going ok until I decided to import a custom JWTService inside this jwt.strategy which contains its own JWTModule but Nest doesn't seems to recognize it. I can use the JWTService in other services but it doesn't work inside the strategy. What should I do ? What am I doing wrong ?
The NEST Message:
[Nest] 53 - 09/22/2022, 6:32:25 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the JwtStrategy (ConfigService, ?). Please make sure that the argument Object at index [1] is available in the AuthModule context.
Potential solutions:
- If Object is a provider, is it part of the current AuthModule?
- If Object is exported from a separate #Module, is that module imported within AuthModule?
#Module({
imports: [ /* the Module containing Object */ ]
})
Error: Nest can't resolve dependencies of the JwtStrategy (ConfigService, ?). Please make sure that the argument Object at index [1] is available in the AuthModule context.
Potential solutions:
- If Object is a provider, is it part of the current AuthModule?
- If Object is exported from a separate #Module, is that module imported within AuthModule?
#Module({
imports: [ /* the Module containing Object */ ]
})
The JWTModule:
import { Module } from '#nestjs/common';
import { JwtModule } from '#nestjs/jwt';
import { jwtOptions } from './jwt.config';
import { JWTService } from './jwt.service';
#Module({
imports: [JwtModule.registerAsync(jwtOptions)],
providers: [JWTService],
exports: [JWTService],
})
export class JWTModule {}
The JWTService:
import { Request } from 'express';
import { DecodeOptions } from 'jsonwebtoken';
import { Injectable, UnprocessableEntityException } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { JwtService, JwtSignOptions, JwtVerifyOptions } from '#nestjs/jwt';
import { CookieHttpConfig } from '../auth';
#Injectable()
export class JWTService {
constructor(
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
sign(payload: string | object | Buffer, options?: JwtSignOptions) {
return this.jwtService.sign(payload, options);
}
async signAsync(payload: string | object | Buffer, options?: JwtSignOptions) {
return this.jwtService.signAsync(payload, options);
}
verify(token: string, options?: JwtVerifyOptions) {
return this.jwtService.verify(token, options);
}
async verifyAsync(token: string, options?: JwtVerifyOptions) {
return this.jwtService.verifyAsync(token, options);
}
decode(token: string, options?: DecodeOptions) {
return this.jwtService.decode(token, options);
}
async getToken(tokenPayload: any): Promise<string> {
try {
const token: string = await this.jwtService.signAsync(tokenPayload);
return `Bearer ${token}`;
} catch (error) {
throw new UnprocessableEntityException(error.message);
}
}
async refreshToken(
cookieName: string,
request: Request,
payload: any,
): Promise<void> {
const token: string = await this.getToken(payload);
request.res.cookie(cookieName, token, CookieHttpConfig.Options());
}
}
jwt.strategy:
import { JWTService } from '#app/common';
import { Injectable } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { PassportStrategy } from '#nestjs/passport';
import { Request } from 'express';
import { ExtractJwt, Strategy } from 'passport-jwt';
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly configService: ConfigService,
private readonly jwtService: JWTService,
) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
(request: Request) => {
try {
const token = request.signedCookies['Authorization'].split(' ')[1];
return token;
} catch (error) {
return null;
}
},
]),
ignoreExpiration: false,
secretOrKey: configService.get('AUTH_JWT_SECRET'),
});
}
async validate(request: Request, payload: any): Promise<any> {
const tokenPayload = {
email: payload.email,
id: payload.id,
};
await this.jwtService.refreshToken('Authorization', request, tokenPayload);
return tokenPayload;
}
}
Extra information about my project:
I divided the project into a monorepo, so I imported the JWTModule inside the AuthModule but it still doesn't work. The jwt.strategy.ts and the JWTModule is inside a shared lib created at the same level as the apps folders containing the microservices.
The AuthModule:
import { Module } from '#nestjs/common';
import { PassportModule } from '#nestjs/passport';
import { UsersModule } from '../users/users.module';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import {
AuthLibModule,
JWTModule,
JwtStrategy,
LocalStrategy,
} from '#app/common';
import { Web3Module } from '../web3/web3.module';
import { VonageModule } from '#app/common';
#Module({
imports: [
UsersModule,
PassportModule,
JWTModule,
Web3Module,
VonageModule,
AuthLibModule,
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
})
export class AuthModule {}

How to open a modal in ionic 5?

I want to open a modal in ionic 5. But somehow I can't find the component.module.ts file where I can export the modals/componets that I want to use. Did they change that system, how is it done with ionic 5? Do you know a piece of documentation for that? The whole system seems to have changed like there is always a page-routing.module.ts. in every page file.
There is nothing new changes for opening modal.
Add modalPage or modalComponent to app.module.ts [ Or Home.module.ts if lazy-loaded ] in entryComponents and declarations
app.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { FolderPageRoutingModule } from './folder-routing.module';
import { FolderPage } from './folder.page'; //from where you open
import { ModalPage } from '../modal/modal.page';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
FolderPageRoutingModule
],
declarations: [ModalPage],
entryComponents: [ModalPage] //modal page
})
export class FolderPageModule {}
and open you modal from corresponding page.
async presentModal() {
const modal = await this.modalController.create({
component: ModelComponent,
componentProps: { value: 123 }
});
await modal.present();
}
Hope this help.

Custom ngx-translate loader, receiving cannot set property 'http' of undefined

I'm setting up a Ionic 4 project using ngx-translate and a custom loader to load JSON translations from an external domain. I've been following this guys take on it: https://forum.ionicframework.com/t/ngx-translate-translatehttploader-with-external-url/99331/4
Stackblitz link: https://stackblitz.com/edit/ionic-v4-jdfbh6
So this is my custom loader (provider).
#Injectable()
export class TranslationProvider implements TranslateLoader {
constructor(private http: HttpClient) {
console.log('Hello TranslationProvider Provider');
}
getTranslation(lang: string): Observable<any> {
return Observable.create(observer => {
this.http.get<any>(Environment.base_api + '/static/translations/' + lang + 'json', {
headers: {'Content-Type': 'application/json'}}).subscribe((res: Response) => {
observer.next(res.json());
observer.complete();
});
});
}
}
and in my app.module.ts (imports):
imports: [
BrowserModule,
IonicModule.forRoot(App),
IonicStorageModule.forRoot(),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (TranslationProvider),
deps: [HttpClient]
}
})
],
The error message I receive is:
TypeError: Cannot set property 'http' of undefined at TranslationProvider (http://localhost:8100/build/main.js:1073:19)
I made a working sample app, here's the gist:
https://gist.github.com/olivercodes/a34be66e5b69edcd96038e5a4518b16e
You need to change #Injectable() to
#Injectable({
providedIn: 'root'
})
Also, make sure these are your import locations:
// In the service file
import { HttpClient } from '#angular/common/http';
import { TranslateLoader } from '#ngx-translate/core'
// in app.module
import { TranslateLoader } from '#ngx-translate/core'
import { HttpClient, HttpClientModule } from '#angular/common/http';
Use my provided gist and make sure your imports are right.

No Provider for AuthHttp! Angular2-Jwt provider issue

At least I thought I was providing correctly. Below are the relevant snippets of my app.module file and the service in which I use AuthHttp. I followed the configuration in the ReadMe for creating the factory method to provide for AuthHttp, but there is a persisting issue with it not being recognized in my service. I've read the literature on nested dependency injections, and I feel as though I'm doing things correctly.
app.module.ts
import { Http, RequestOptions } from '#angular/http';
import { provideAuth, AuthHttp, AuthConfig } from 'angular2-jwt/angular2-jwt';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig(), http, options);
}
#NgModule({
declarations: [
AppComponent,
ButtonFormComponent,
...
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule,
AppRoutingModule
],
providers: [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
},
employee.service.ts
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { ApiSettings } from './api-settings';
#Injectable()
export class EmployeeService {
api: String;
auth: String;
constructor(private http: Http, private authHttp: AuthHttp) {
this.api = ApiSettings.API;
this.auth = ApiSettings.Auth;
}
You can get rid of this issue by just using following import in your app.module.ts, here the key import for you is, AUTH_PROVIDERS.
Also, make sure you include AUTH_PROVIDERS in the providers array.
import { AuthHttp, AUTH_PROVIDERS, provideAuth, AuthConfig } from
'angular2-jwt/angular2-jwt';
#NgModule({
providers: [AUTH_PROVIDERS]
})

Ionic 2 HTTP request not working - Angular 2

Hi I'm trying to do a simple Http GET request, but can't get it to work in ionic v2 Beta...
here is my app.js:
import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
import {HTTP_BINDINGS} from 'angular2/http';
#App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
providers: [HTTP_BINDINGS],
config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
static get parameters() {
return [[Platform]];
}
constructor(platform) {
this.rootPage = TabsPage;
platform.ready().then(() => {
});
}
}
and this is my page1.js:
import {Page} from 'ionic-angular';
import {Http} from 'angular2/http';
#Page({
templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
constructor(http:Http) {
this.mget = http.get("https://httpbin.org/ip")
.subscribe(data => {
var alert = Alert.create({
title: "Your IP Address",
subTitle: data.json().origin,
buttons: ["close"]
});
this.nav.present(alert);
}, error => {
console.log(JSON.stringify(error.json()));
});
}
}
When adding http:Http to the constructor -> constructor(http:Http) the whole app goes blank in browser...
And I get an error in Console:
Error: Cannot find module "../page1/page1"
I've also tried this in Page1.js:
export class Page1 {
constructor() {
}
makeGetRequest() {
this.http.get("https://httpbin.org/ip")
.subscribe(data => {
var alert = Alert.create({
title: "Your IP Address",
subTitle: data.json().origin,
buttons: ["close"]
});
this.nav.present(alert);
}, error => {
console.log(JSON.stringify(error.json()));
console.log('yolo')
alert('hello');
});
}
}
and then call makeGetRequest() on (click) in page1.html
but it returns these exeptions:
EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: this.http is undefined
please help!
:)
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
THIS IS THE SOLUTION:
page1.js:
import {Page} from 'ionic-angular';
import {Http} from 'angular2/http';
#Page({
templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
static get parameters(){
return [Http];
}
constructor(http) {
this.http = http;
this.mget = this.http.get("https://httpbin.org/ip")
.subscribe(data => {
console.log(data);
}, error => {
console.log('faild');
});
}
}
app.js:
import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
import { HTTP_PROVIDERS } from 'angular2/http';
#App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
providers: [HTTP_PROVIDERS],
config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
static get parameters() {
return [[Platform]];
}
constructor(platform) {
this.rootPage = TabsPage;
platform.ready().then(() => {
});
}
}
Please try this
export class Page1 {
static get parameters(){
return [Http];
}
constructor(http) {
this.http = http;
this.mget = this.http.get("https://httpbin.org/ip")
.subscribe(data => {
var alert = Alert.create({
title: "Your IP Address",
subTitle: data.json().origin,
buttons: ["close"]
});
this.nav.present(alert);
}, error => {
console.log(JSON.stringify(error.json()));
});
}
}
I would recommend you to write the get request inside a separate service and inject it in your page.
Also have a look at this - http://tphangout.com/?p=113
Detailed and simple instructions are given there for making a simple GET request from an Ionic 2 app.
I believe you need to
import { HTTP_PROVIDERS } from 'angular2/http';
in your app.js instead of HTTP_BINDINGS and change providers: [HTTP_BINDINGS] to providers: [HTTP_PROVIDERS]
See Angular2 docs