hasAttribute in DOM not working properly

2019-09-02 16:00发布

问题:

I have this form in an tect.html file and I want to test if the button is disabled or not:

<button id="ref_button"....[disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">

I am using protractor, cucumber, and chai dom to test if this button is disabled when the form data are invalid, so I check its attribute disabled like this:

  JSDOM.fromFile("file.html").then(dom => {
   dom.window.document.getElementById("ref_button").has.attr('disabled').should.be.true;
     
    });
  });

Now the test fails because it always finds the attribute disabled, when the button is disabled or not, when the datas are valid or not.

What am I doing wrong?

回答1:

I think the attribute [disabled] does NOT exist on button element( that's why it's always true). It's the attribute disabled which you have to look for( without [ and ] markup. It's binding syntax.

So when thinking about it, this should work: (did not test...)

dom.window.document.getElementById("ref_button").should.not.have.attr("disabled");

But probably this will always output false since a button does have that attribute. To make this consistently work you should take the value of the disabled attribute and check wheter it's true.

dom.window.document.getElementById("ref_button").getAttribute("disabled").toBeTruethy().

I actually don't know if toBeTruethy() does exist in chai but my point here is, that you should check the value of an attribute and not just if an attribute exists in general.

One other thing to mention is this:

element(by.css("*[id='field_nombre']")).click();
element(by.css("*[id='field_nombre']")).sendKeys('').then(callback);

I guess click() is also an asynchronous function and in above example keys are sent before click() has finished it's execution. This would be correct I think:

element(by.css("*[id='field_nombre']")).click().then(function() {
  element(by.css("*[id='field_nombre']")).sendKeys('').then(callback);
});


回答2:

For angularJs, you should use directive ng-disabled in your html

from official documentation:

A special directive is necessary because we cannot use interpolation inside the disabled attribute. See the interpolation guide for more info.