开玩笑:在setImmediate或process.nextTick回调中测试不会失败 [英] Jest: tests can't fail within setImmediate or process.nextTick callback

查看:88
本文介绍了开玩笑:在setImmediate或process.nextTick回调中测试不会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为需要在其componentWillMount方法中完成异步操作的React组件编写测试. componentWillMount调用作为prop传递的函数,该函数返回promise,然后在测试中模拟该函数.

I'm trying to write a test for a React component that needs to complete an asynchronous action in its componentWillMount method. componentWillMount calls a function, passed as a prop, which returns a promise, and I mock this function in my test.

这很好,但是如果在调用setImmediateprocess.nextTick的过程中测试失败,则Jest不会处理该异常,并且该异常会过早退出.在下面,您可以看到我什至试图捕获此异常,但无济于事.

This works fine, but if a test fails in a call to setImmediate or process.nextTick, the exception isn't handled by Jest and it exits prematurely. Below, you can see I even try to catch this exception, to no avail.

我如何在Jest中使用setImmediatenextTick之类的东西?对于这个问题,可以接受的答案是我尝试失败的实现:反应酶-测试`componentDidMount`异步调用.

How can I use something like setImmediate or nextTick with Jest? The accepted answer to this question is what I'm trying to implement unsuccessfully: React Enzyme - Test `componentDidMount` Async Call.

it('should render with container class after getting payload', (done) => {
  let resolveGetPayload;
  let getPayload = function() {
    return new Promise(function (resolve, reject) {
      resolveGetPayload = resolve;
    });
  }
  const enzymeWrapper = mount(<MyComponent getPayload={getPayload} />);

  resolveGetPayload({
    fullname: 'Alex Paterson'
  });

  try {
    // setImmediate(() => {
    process.nextTick(() => {
      expect(enzymeWrapper.hasClass('container')).not.toBe(true); // Should and does fail
      done();
    });
  } catch (e) {
    console.log(e); // Never makes it here
    done(e);
  }
});

笑话v18.1.0

节点v6.9.1

推荐答案

另一个可能更清洁的解决方案,使用async/await并利用jest/mocha的功能来检测返回的诺言:

Another potentially cleaner solution, using async/await and leveraging the ability of jest/mocha to detect a returned promise:

function currentEventLoopEnd() {
  return new Promise(resolve => setImmediate(resolve));
}

it('should render with container class after getting payload', async () => {
  let resolveGetPayload;
  let getPayload = function() {
    return new Promise(function (resolve, reject) {
      resolveGetPayload = resolve;
    });
  }
  const enzymeWrapper = mount(<MyComponent getPayload={getPayload} />);

  resolveGetPayload({
    fullname: 'Alex Paterson'
  });

  await currentEventLoopEnd(); // <-- clean and clear !

  expect(enzymeWrapper.hasClass('container')).not.toBe(true);
});

这篇关于开玩笑:在setImmediate或process.nextTick回调中测试不会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆