CSS issue testing AngularJS directives with Karma + Jasmine

若如初见. 提交于 2019-12-05 03:59:52

Ok, the problem is very simple and stupid... I wonder why I lost so much time to realize it :P So... the CSS are perfectly injected by Karma by specifying them in the config file, like I've done as the first approach (there is no need for other plugin or black magic), but... CSS styles are not applied to elements until they get added to the DOM! and this is not an issue related to karma, angular, jasmine or what else... this is how a browser engine works! A browser parses CSS definitions and it renders elements in the page according, but when in angular test I write:

var element = angular.element('<my-directive></my-directive>');
$compile(element)(scope);

I'm dealing with in-memory DOM nodes, which are unknown to all but my JavaScript code! How should the browser engine apply CSS to an in-memory node living in a js variable? It can't obviously... it can only traverse the nodes tree in the page, so... the "fix" is very simple: I have to add the element to the DOM:

angular.element(document).find('body').append(element);

From the sounds of your situation, you're looking to test if the DOM is in a certain state. I found a plugin that looks like it was designed with this use case in mind: jasmine-jquery. Even though you're using AngularJs for your DOM manipulation, this extension will still let you test the resultant DOM's state.

In particular I think you should have a look at the StyleSheet Fixtures which lets you inject CSS in to the test.

Disclaimer: I haven't tested any of this yet, the answer is just the result of research.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!