각도기를 사용하여 요소에 클래스가 있는지 테스트하는 방법은 무엇입니까?
나는 각도 앱을 e2e 테스트하기 위해 각도기를 시도하고 있으며 요소에 특정 클래스가 있는지 여부를 감지하는 방법을 찾지 못했습니다.
제 경우에는 테스트에서 제출 버튼을 클릭하고 이제 form [name = "getoffer"]에 .ngDirty 클래스가 있는지 알고 싶습니다. 해결책은 무엇일까요?
describe('Contact form', function() {
beforeEach(function(){
browser.get('http://localhost:9000');
element(by.linkText('Contact me')).click();
});
it('should fail form validation, all fields pristine', function() {
element(by.css('.form[name="getoffer"] input[type="submit"]')).click();
expect(element(by.name('getoffer'))).toHaveClass('ngDirty'); // <-- This line
});
});
toMatch()
허용되는 답변에서 와 같이 using을 사용하여 찾아야 할 한 가지 문제 는 부분 일치입니다. 예를 들어, 당신이 클래스를 가질 수 요소가 있다고 가정하자 correct
와 incorrect
, 당신은이 클래스를 가지고 테스트 할 correct
. 을 사용 expect(element.getAttribute('class')).toMatch('correct')
하면 요소에 incorrect
클래스 가 있어도 true를 반환합니다 .
나의 제안:
정확히 일치하는 항목 만 허용하려면 이에 대한 도우미 메서드를 만들 수 있습니다.
var hasClass = function (element, cls) {
return element.getAttribute('class').then(function (classes) {
return classes.split(' ').indexOf(cls) !== -1;
});
};
다음과 같이 사용할 수 있습니다 ( expect
Protractor에서 자동으로 promise를 해결 한다는 사실을 활용 ).
expect(hasClass(element(by.name('getoffer')), 'ngDirty')).toBe(true);
Jasmine과 함께 Protractor를 사용 toMatch
하는 경우 정규식으로 일치 하는 데 사용할 수 있습니다 .
expect(element(by.name('getoffer')).getAttribute('class')).toMatch('ngDirty');
또한 toContain
필요한 경우 목록 항목과 일치합니다.
가장 간단한 것은 :
expect(element.getAttribute('class')).toContain("active");
Sergey K의 답변을 기반으로 사용자 정의 매처를 추가하여이를 수행 할 수도 있습니다.
(커피 스크립트)
beforeEach(()->
this.addMatchers({
toHaveClass: (expected)->
@message = ()->
"Expected #{@actual.locator_.value} to have class '#{expected}'"
@actual.getAttribute('class').then((classes)->
classes.split(' ').indexOf(expected) isnt -1
)
})
)
그런 다음 다음과 같은 테스트에서 사용할 수 있습니다.
expect($('div#ugly')).toHaveClass('beautiful')
그렇지 않은 경우 다음 오류가 발생합니다.
Message:
Expected div#ugly to have class beautiful
Stacktrace:
Error: Expected div#ugly to have class 'beautiful'
시도해 보셨습니까 ...
var el = element(by.name('getoffer'));
expect(e.getAttribute('class')).toBe('ngDirty')
또는 위의 변형 ...
이 매처를 만들었는데 약속에 싸서 2 번 돌려야 했어요
this.addMatchers({
toHaveClass: function(a) {
return this.actual.getAttribute('class').then(function(cls){
var patt = new RegExp('(^|\\s)' + a + '(\\s|$)');
return patt.test(cls);
});
}
});
내 테스트에서 나는 이제 다음과 같이 stuf를 할 수 있습니다.
var myDivs = element.all(by.css('div.myClass'));
expect(myDivs.count()).toBe(3);
// test for class
expect(myDivs.get(0)).not.toHaveClass('active');
이것은 요소에 여러 클래스가 있거나 요소에 클래스 속성이 전혀 없을 때도 작동합니다.
Here a Jasmine 1.3.x custom toHaveClass
matcher with negation .not
support plus wait up to 5 seconds (or whatever you specify).
Find the full custom matcher to be added on your onPrepare block in this gist
Sample usage:
it('test the class finder custom matcher', function() {
// These guys should pass OK given your user input
// element starts with an ng-invalid class:
expect($('#user_name')).toHaveClass('ng-invalid');
expect($('#user_name')).not.toHaveClass('ZZZ');
expect($('#user_name')).toNotHaveClass('ZZZ');
expect($('#user_name')).not.toNotHaveClass('ng-invalid');
// These guys should each fail:
expect($('#user_name')).toHaveClass('ZZZ');
expect($('#user_name')).not.toHaveClass('ng-invalid');
expect($('#user_name')).toNotHaveClass('ng-invalid');
expect($('#user_name')).not.toNotHaveClass('ZZZ');
});
function checkHasClass (selector, class_name) {
// custom function returns true/false depending if selector has class name
// split classes for selector into a list
return $(selector).getAttribute('class').then(function(classes){
var classes = classes.split(' ');
if (classes.indexOf(class_name) > -1) return true;
return false;
});
}
This is how I do it at least, without the need to use the expect function. This function simply returns true if the class is inside the element and false if not. This also uses promises so you would use it like:
checkHasClass('#your-element', 'your-class').then(function(class_found){
if (class_found) console.log("Your element has that class");
});
Edit: I just realized this is essentially the same as the top answer
One way to achieve this would be to use xpath and use contains()
Example:
var expectElementToHaveClass = function (className) {
var path = by.xpath("//div[contains(@class,'"+ className +"')]");
expect(element.all(path).count()).to.eventually.be.eq(1);
};
You can use the CSS parser to handle this by checking if an element with the given class exists:
expect(element(by.css('.form[name="getoffer"].ngDirty')).isPresent()).toBe(true);
참고URL : https://stackoverflow.com/questions/20268128/how-to-test-if-an-element-has-class-using-protractor
'Nice programing' 카테고리의 다른 글
C / C ++ : 강제 비트 필드 순서 및 정렬 (0) | 2020.10.04 |
---|---|
interface {}를 int로 변환 (0) | 2020.10.04 |
Spark Kill 실행 애플리케이션 (0) | 2020.10.04 |
doxygen을 사용하여 Python 코드를 문서화하는 방법 (0) | 2020.10.04 |
키가 vim에서 무언가에 바인딩되었는지 감지 (0) | 2020.10.04 |