Element is undefined in angular - javascript

I am testing an app in angular and JHipster.
I try to test a label like this:
<label #hiddenLabel class="form-control-label" jhiTranslate="oncosupApp.paciente.nombre" for="field_nombre" >Nombre</label>
and it gives the error that the hidden is undefined, that means that it doesn't take the reference of the HTML element.
Then I try without jhiTranslate like this:
<label #hiddenLabel class="form-control-label" for="field_nombre" >Nombre</label>
and everything works perfectly.
The testBed code is here and I haven't included any translation functionality from jhi cause I am a newbie in JHI and don't know what to insert:
imports.....
describe('Component Tests', () => {
describe('Paciente Management Dialog Component', () => {
let comp: PacienteDialogComponent;
let fixture: ComponentFixture<PacienteDialogComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [OncosupTestModule,
OncosupSharedModule,
BrowserModule,
FormsModule,
],
declarations: [PacienteDialogComponent,
],
providers: [
JhiAlertService, ],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
//.overrideTemplate(PacienteDialogComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PacienteDialogComponent);
comp = fixture.componentInstance;
//service = fixture.debugElement.injector.get(PacienteService);
//mockEventManager = fixture.debugElement.injector.get(JhiEventManager);
//mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal);
});
fit ('first test asdsadfdfd', async(() => {
expect(comp.hidden.nativeElement.innerHTML).toContain('Nombre');
}));
My component :
imports...
#Component({
selector: 'jhi-paciente-dialog',
template: require('./paciente-dialog.component.html'),
styleUrls: [
'paciente.css'
],
})
export class PacienteDialogComponent implements OnInit {
#ViewChild('hiddenLabel') hidden: ElementRef;
This means that jhiTranslate is not permitting me to take the reference of the HTML element. How can I fix this? I cannot remove jhiTranslate, cause the app is not mine. I just need to test it.

Related

HTML code only shows {{title}} instead of variable name

I'm currently following this tuturial: https://www.youtube.com/watch?v=WlAq06Z_25Y&list=PL8p2I9GklV45JZerGMvw5JVxPSxCg8VPv&index=4
what i want
but html only shows
what i get:
i'm trying to learn angular but it's verry confusing if you try to follow a turturial but some things just dont match up
code:
app.module.ts code:
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'blog';
}
app.component.html code:
<h1>Hello World !</h1>
<h2>{{title}}</h2>
app.component.spec.ts code:
import { TestBed } from '#angular/core/testing';
import { RouterTestingModule } from '#angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'blog'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('blog');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('blog app is running!');
});
});
You need to run your app with ng serve and then verify your output on localhost:4200.
In case you need to run it on any other port, use ng serve --port:portnumber
Try creating a public method to pass it between your components:
export class AppComponent {
public title = "blog";
}
<h2>{{ title }}</h2>
i used port 5200 but i should use port 4200 instead. now it works

How to provide injected values while unit testing a component in angular5+

I am writing tests for a component that is initialized dynamically as a modal (entryComponent). Inputs for this component are retrieved via injector.
I need a way to provide these inputs in my component creation step in beforeEach.
this.modalService.create({
component: sampleComponent, inputs: {
test: 'testMsg'
}
});
SampleComponent:
#Modal()
#Component({
selector: 'sample-component',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {
test: string;
constructor(private injector: Injector) {
}
ngOnInit() {
this.test= this.injector.get('test');
}
}
Test for sampleComponent:
describe('sampleComponent', () => {
let component: SampleComponent;
let fixture: ComponentFixture<SampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SampleComponent],
imports: [
ModalModule,
BrowserAnimationsModule,
],
providers: [
ModalService,
]
})
.compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(SampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.ngOnInit();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
test fails with:
Error: StaticInjectorError(DynamicTestModule)[test]:
StaticInjectorError(Platform: core)[test]:
NullInjectorError: No provider for test!
How do provide value for 'test' in this case?
In providers, provide values for the injected values that component is expecting:
providers: [
{ provide: 'test', useValue: 'valueOfTest' }
]

No provider for TestingCompilerFactory

This is my test file and I am trying to identify the error preventing me from running a successful test:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { Component, Directive, Input, OnInit } from '#angular/core';
import { TestComponent } from './test.component';
import { NgbDropdownModule, NgbCollapse } from '#ng-bootstrap/ng-bootstrap';
import { CommonModule } from '#angular/common';
import { Routes } from '#angular/router';
import { RouterTestingModule } from '#angular/router/testing';
import { NO_ERRORS_SCHEMA } from '#angular/core';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '#angular/platform-browser-dynamic/testing';
let comp: TestComponent;
let fixture: ComponentFixture<MyComponent>;
describe('TestComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ TestComponent ],
providers: [
// DECLARE PROVIDERS HERE
{ provide: TestingCompilerFactory }
]
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(TestComponent);
comp = fixture.componentInstance;
});
}));
it('should be created', () => {
expect(TestComponent).toBeTruthy();
});
I am getting this error which I guess is because I am not wrapping it correctly.
error TS1005: ';' expected.
But I also get
No provider for TestingCompilerFactory
First fix your syntax error1,2
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [{ provide: TestingCompilerFactory }]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(TestComponent);
comp = fixture.componentInstance;
});
}); // excess `)` removed
Now, onto the noteworthy error
A provider takes can take two forms.
The first is a value that acts as both the value provided and the key under which it is registered. This commonly takes the form of a class as in the following example
const Dependency = class {};
#NgModule({
providers: [Dependency]
}) export default class {}
The second is an object with a provide property specifying the key under which the provider is registered and one or more additional properties specifying the value being provided. A simple example is
const dependencyKey = 'some key';
const Dependency = class {};
#NgModule({
providers: [
{
provide: dependencyKey,
useClass: Dependency
}
]
}) export default class {}
From the above it you can infer that you failed to specify the actual value provided under the key TestingCompilerFactory.
To resolve this write
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [
{
provide: TestingCompilerFactory,
useClass: TestingCompilerFactory
}
]
})
which is redundant and can be replaced with
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [TestingCompilerFactory]
})
as described above.
Notes
In the future do not post questions that include such an obvious error - fix it yourself instead.
Do not post two questions as one.

Angular 5 jasmine tests, component not compiling

I'm trying to write a simple unit test, but cannot get my template to compile. The AppComponent has one variable called text which renders to an h1 tag. When testing the html, this always comes back as ''. Does anyone know what I'm missing here?
Test code
import {TestBed, async, ComponentFixture} from '#angular/core/testing';
import {AppComponent} from './app.component';
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
const mainTitle = 'Angular Unit Testing';
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
}));
it(`should render ${mainTitle} to an H1 tag`, async(() => {
const compiled = fixture.debugElement.nativeElement;
console.log('here', compiled.querySelector('h1'));
expect(compiled.querySelector('h1').textContent).toEqual(mainTitle);
}));
});
Component code
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
text = 'Angular Unit Testing';
}
HTML
<h1>{{text}}</h1>
You must set "text" public property of component-only then it will be rendered inside h1 tag
it(`should render ${mainTitle} to an H1 tag`, async(() => {
const compiled = fixture.debugElement.nativeElement;
component.text = 'Angular Unit Testing';
fixture.detectChanges();
expect(compiled.querySelector('h1').textContent).toEqual(mainTitle);
}));

Jasmine: Mocking ViewChild component, Angular 2

I have Parent Component which has View child component associated with it. I'm trying to set up unit test for parent component but i'm not able to override the View Child component with mock class. I tried NO_ERRORS_SCHEMA, CUSTOM_SCHEMA in Schema provider and also used ng2-mock-component.
describe('Mobile Application Card:', () => {
let comp: MobileAppCardComponent;
let fixture: ComponentFixture<MobileAppCardComponent>;
beforeEach(() => {
const mock = MockComponent({ selector: 'bt-modal'}); // View Child Component.
TestBed.configureTestingModule({
declarations: [MobileAppCardComponent, mock],
providers: [{provide: MobileAppService, useValue: serviceStub},
{provide: ToastService, useValue: {}},
{provide: Router, userValue: null }
]
});
fixture = TestBed.createComponent(MobileAppCardComponent);
});
});

Categories

Resources