简体   繁体   中英

Asserting all checkboxes are checked

I have 5 checkboxes with the same name property relative-view .

I want to assert that all of them are checked. I can do this to check the first and last one

expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]').last().prop("checked")).toBe(true);

But I don't know how to check them all. I have tried the following but I get an error saying undefined is not a function

expect(element.find('input[name="relative-view"]')[0].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[1].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[2].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[3].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[4].prop("checked")).toBe(true);

How can I do this?

[n] notation returns DOM elements which don't have .prop() - that's jQuery API. Use .eq() :

var boxes = element.find('input[name="relative-view"]');

expect(boxes.eq(0).prop("checked")).toBe(true);
expect(boxes.eq(1).prop("checked")).toBe(true);
expect(boxes.eq(2).prop("checked")).toBe(true);
expect(boxes.eq(3).prop("checked")).toBe(true);
expect(boxes.eq(4).prop("checked")).toBe(true);

An alternative approach would be to use the standard .checked property:

var boxes = element.find('input[name="relative-view"]').get();

expect(boxes[0].checked).toBe(true);
expect(boxes[1].checked).toBe(true);
expect(boxes[2].checked).toBe(true);
expect(boxes[3].checked).toBe(true);
expect(boxes[4].checked).toBe(true);

Also, try just iterating over the jQuery collection:

$('input[name="relative-view"]', element).each(function () {
    expect(this.checked).toBe(true);
});

You can write a function which will go through all checkboxes and return false if any of them is not checked. Use:

function CheckAllCheckboxes(){
    var _RetValue = true;
    $('input[name="relative-view"]').each(function(){
        if($(this).prop("checked") != true)
            _RetValue = false;
            return false; // quit from each()
    }
    return _RetValue;
}

Then you can use

expect(CheckAllCheckboxes()).toBe(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM