如何在Cypress中测试带有图像的旋转木马?



我需要在Cypress中为carousel与图像编写自动化测试。

我有这样的东西:

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="..." alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="..." alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="..." alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>

旋转木马自动改变。活动图像获得类slider_wrapper__activeSlide__2LNke",而另一个图像具有类slider_wrapper__nextSlide__1Vnk4"。我想检查一下carousel是否显示在页面上,活动图像是否有正确的类。

我尝试使用。should ('include'),但它不起作用:(

您可以使用.find()来查询生成元素下面的元素。

cy.get('.carousel-item.active') // get the active div
.find('img') // get the img element underneath the above div
.should('be.visible') // check that the element is visible
.and('have.class', 'slider_wrapper__activeSlide__2LNke'); // check for the active image class.

如果你需要检查每个旋转木马项目,你必须使用JQuery的hasClass

cy.get('.carousel-item') // retrieve all elements with carousel-item class
.each(($item) => { // iterate through all elements
cy.wrap($item) // wrap the yielded element
.find('img') // find the img
.should('have.class', $item.hasClass('active') ? 'slider_wrapper__activeSlide__2LNke' : 'slider_wrapper__nextSlide__1Vnk4'); 
// ^ ternary to determine which class we are checking for

旋转木马自动改变。为了测试这方面,使用cy.clock()来"冻结"。移动,然后cy.tick(3000)滑动到下一张图像(假设延迟3秒)。

cy.clock()
cy.get('div#carouselExampleControls')
.find('div.carousel-item.active')
.invoke('index')
.should('eq', 0)                    // first image is active
cy.tick(3000)
cy.get('div#carouselExampleControls')
.find('div.carousel-item.active')
.invoke('index')
.should('eq', 1)                    // second image is active

尽量不要使用像__2LNke这样后缀的类,它们可能由框架生成并在下次构建时更改。

如果要检查,请使用前缀部分slider_wrapper__activeSlideslider_wrapper__nextSlide

cy.get('[class*="slider_wrapper__nextSlide"]')  // partial matching, more robust

最新更新