Reputation: 25793
In have an Angular component that renders a span like this:
<span class="buy" [style.width.%]="percent"></span>
In my unit test, I want to check if the inline style has the right percentage number. For example, if the component renders as follows, I want to test if the percentage is 50%:
<span class="buy" style="width: 50%;"></span>
Currently this is the best I could do:
const debugElm = fixture.debugElement;
const htmlElm = debugElm.nativeElement;
const buyBar = htmlElm.querySelector('.buy');
expect(buyBar.getAttribute('style')).toEqual('width: 0%;');
I don't like testing the value of the style
attribute to equal the string width: 0%;
. Is there a better way to access the width property of the inline style?
Upvotes: 3
Views: 5417
Reputation: 527
So people already talk about the solution and here is my thought.
Why bothering about the '50%' number though.
If your point is to test the width of '.buy' class to be 50% of something
we just simply
it('element with buy class should have width equal 50% of parent element', () => {})
and your test case could be(let me assume that you have a parent class)
<div class="parent"><span class="buy" style="width: 50%;"></span></div>
const debugElm = fixture.debugElement;
const htmlElm = debugElm.nativeElement;
const parent = htmlElm.querySelector('.parent');
const buyBar = htmlElm.querySelector('.buy');
const parentStyle = getComputedStyle(parent);
const barStyle = getComputedStyle(buyBar);
expect(barStyle.width / parentStyle.width).toEqual(0.5);
Here I'm just reuse the code of others above so not so sure the expect
function could work. but I think this could be a workaround for your test case.
Upvotes: 3
Reputation: 13682
You could try something like this:
const style = document.defaultView.getComputedStyle(buyBar, null);
expect(style.getPropertyValue('width')).toEqual('0%');
Upvotes: 0