如何处理Cypress测试中的去抖输入?

问题描述 投票:0回答:1

在赛普拉斯 E2E 测试中处理去抖输入的推荐方法是什么。

例如,假设我有以下使用

lodash/debounce

的组件
import React, { useState, useCallback } from 'react';
import _ from 'lodash';

const DebouncedInput = () => {
  const [query, setQuery] = useState("");
  const [searchResult, setSearchResult] = useState("");

  // The debounced function
  const searchApi = useCallback(
    _.debounce(async (inputValue) => {
      setSearchResult(`User searched for: ${inputValue}`);
    }, 200),
    []
  );

  const handleChange = (e) => {
    setQuery(e.target.value);
    searchApi(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={handleChange}
        placeholder="Type something..."
      />
      {searchResult && <p>{searchResult}</p>}
    </div>
  );
};

export default DebouncedInput;

我该如何确保我的 Cypress 测试不会不稳定?

我认为有两种方法:

  • 处理 cy.clock() 并使用 cy.tick()
cy.get('[data-cy="foo"]').type('hey').tick(250)

  • 利用
    cy.type
    delay
    选项
cy.get('[data-cy="foo"]').type('hey', {delay: 250});

我尝试了两种方法,似乎都有效。但我不确定是否确实有推荐的方法来做到这一点,或者一种方法是否比另一种更好。

reactjs cypress lodash
1个回答
0
投票

可以使用cy.wait(与使用的debounce相同的延迟时间)。

_.debounce((searchValue: string) => {
 ...       
}, 5000)


//in search.cy.js
it("assert no items are existing", () => {
  cy.get("[data-test=search-input]").type("random 12345...");
  cy.wait(5000);
  cy.get(".no-items-panel").should("exist");
});
© www.soinside.com 2019 - 2024. All rights reserved.