I try to test if my component will change background color properly after passing an Input value. When input value changes the ngClass with adequate class is applied. So when the @Input() type = 'red'
the class of div will change to comp--red
. I've got to the place where the class is applied and the test works as it should but the next test when I check div.style.backgroundColor
doesn't pass.
Test
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({ declarations: [TestComponent] }).compileComponents();
})
);
describe('with template', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should have red background when type is red', () => {
fixture.componentInstance.type = 'red';
fixture.detectChanges();
const div = fixture.debugElement.query(By.css('.comp--red')).nativeElement;
expect(div.style.backgroundColor).toBe('#ff0000');
});
});
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Component
@Component({
selector: 'test-comp',
template: `
<div [ngClass]="'comp--' type">
<ng-content></ng-content>
</div>
`,
styleUrls: ['./test.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class TestComponent {
@Input() type;
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Class
.comp--red {background-color: #ff0000;}
The output is:
Expected '' to be '#ff0000'.
But when I inspect an element it has class comp--red
. Could you give me a hand with this?
CodePudding user response:
element.style
refers to the inline styles on an element, not the styles that are applied to an element via CSS stylesheets. To get the styles currently applied to an element by the browser use:
expect(getComputedStyle(div).backgroundColor).toEqual('#ff0000');
Note: I would think that the test should just cover that the css class
has been applied, rather than testing the color value itself