Karma handles the process of creating HTML files, opening browsers and running tests and returning the results of those tests to the command line. If you use the Angular CLI to manage projects it automatically creates stub Jasmine spec files for you when generating code.
Create an Angular project with jasmine and karma By doing this, the jasmine and karma configuration is resolved for us. Install and create a new project with angular-cli: Install npm -g @angular/cli. Ng new angular-unit-testing angular unit-testing.
A Jasmine spy can stub any function and track all calls to that function and all of its arguments. Jasmine Spies are a powerful tool to use in unit testing because they allow us to focus on the function that is being tested. A spy will only exist in the describe or it block that it is defined.
I have an Angular component that has a <p>
tag with some text. One of the sentences inside of the paragraph is bold. I am trying to write a unit test in Jasmine/Karma to check the innerHTML
content. However, all of my attempts seem to fail. Am I going about this the wrong way? Here is my markup and JavaScript:
Angular component HTML
<p>
Four score and seven years ago our fathers brought forth on this
continent, <b>a new nation</b>, conceived in Liberty, and dedicated to the
proposition that all men are created equal.
</p>
Jasmine Unit Test
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let el: DebugElement;
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
fixture.detectChanges();
});
it('should display "a new nation" as bold text', () => {
const boldText = el.query(By.css('p')).nativeElement;
expect(boldText.innerHTML).toContain('<b>a new nation</b>');
});
});
I get the following failed error with this code:
Expected 'Four score and seven years ago our fathers brought forth on this continent, <b _ngcontent-c1="">a new nation</b>, conceived in Liberty, and dedicated to the proposition that all men are created equal.'.
Note that Angular is injecting its own ID to the <b>
tag. Is this the reason is fails? Is this even the best way to go about this kind of test?
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With