【问题标题】:How can I wait for the `finally` block to run before I expect something in my test?在我期待测试中的某些内容之前,如何等待“finally”块运行?
【发布时间】:2021-10-03 18:27:52
【问题描述】:

我有一个文件要测试,如下所示:

function handleButtonClick() {
  getData().then(() => {
    // Do something here
  }).catch((err) => {
    // Handler error here
  }).finally(() => {
    // Set color state to yellow
  });
}

我的测试看起来像这样

let getDataResolve;
const getData = jest.fn();
getData.mockReturnValue(
  new Promise(res => {
    getDataResolve = res;
  })
);

it('should change color to yellow on button click', async () => {
  const myButton = ...do something to grab the button here;
  fireEvent.click(myButton);
  await getDataResolve({});
  expect(// here expect color is set to yellow);
});

但是我的测试失败了,因为通过在我的测试中调用await getDataResolve({}),我只能触发then 块运行,而expect linefinally block 之前运行。但我想在运行finally 块之后运行expect。无论如何我可以做到这一点吗?我真的不明白finally 块是如何以及何时触发的。非常感谢您的帮助!

【问题讨论】:

  • 嗨,Bravo,感谢您的评论,那么如果我想在我的测试中使用 expect 行,您有什么建议?更改代码以使测试工作显然不是一个好习惯。
  • 组件中的某处会有一个按钮,并且有一个 onClick 处理程序,即 handleButtonClick。在测试中,我能够抓住那个按钮并模拟点击它。我不知道这是否能消除你的困惑。
  • 告诉你什么,因为我似乎很困惑,所以我将删除我的 cmets,也许更了解的人可以提供帮助
  • 尝试将expect 包裹在waitFor 中:await waitFor(() => expect(...));

标签: javascript promise jestjs es6-promise react-testing-library


【解决方案1】:

尝试使用waitFor,finally块正在执行,finally块中设置的值可用,可以使用react测试库的waitFor函数测试

//App.js
export default function App() {
  const [value, setValue] = useState('init');

  const getData = () => {
    return Promise.resolve('')
  }

  function handleButtonClick() {
    getData().then(() => {
      setValue('then');
    }).catch((err) => {
      setValue('error');
    }).finally(() => {
      setValue('finally');
    });
  }
  
  return (
      <button onClick={handleButtonClick} data-testid="btn">{value}</button>
  );
}

//app.test.js
describe("<App />", () => {
  it('check if finally block is called', async() => {
    const { queryByTestId } = render(<App />);
    const btn = queryByTestId('btn');
    fireEvent.click(btn);
    await waitFor(() => expect(queryByTestId('btn')).toHaveTextContent('finally'))
  });
});

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 1970-01-01
    • 2014-10-21
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 2015-06-12
    • 2020-08-16
    相关资源
    最近更新 更多