I am a starter of Angular unit testing with Jasmine and Karma. To test I have written a small component. My component is following:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-input',
template: `{{ message }}`,
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
@Input() message: string;
constructor() { }
ngOnInit() {
}
}
I have the following test spes to test the above component:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InputComponent } from './input.component';
describe('InputComponent', () => {
let component: InputComponent;
let fixture: ComponentFixture<InputComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ InputComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(InputComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should correctly render the passed @Input value', () => {
component.message = 'Hi there';
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.innerHTML).toBe('Hi there');
});
});
This is alright, and the test gives the expected result. But when I separated my HTML in template file, the test runner gives following error:
Expected 'Hi there ' to be 'Hi there'.
After separation, my component and template file looks like following:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
@Input() message: string;
constructor() { }
ngOnInit() {
}
}
Content of my template file is:
{{ message }}
Expected 'Hi there ' to be 'Hi there'.
As you can see, there's a space character after the bound message.
It seems like there's a new-line or any other white-space character in the end of the template file.
Looks like your innerHTML
returns the string with a whitespace in the end.
Expected 'Hi there ' to be 'Hi there'.
Check your template for a new-line or whitespace after {{ message }}
. Many of the IDEs save the template/file with a newline at the end. that might be causing the problem.
You should be using {{message}}
in a span or <p>
that way you can just get the value from the html tag in stead of getting the entire template and run into such issues.
EX:
const mypara = fixture.debugElement.query(By.css('#myParagraph')).nativeElement as HTMLElement;
expect(mypara.innerText).toEqual('Hi there');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.