繁体   English   中英

mocha/chai 如何测试在 then 或 catch 回调中调用方法

[英]mocha/chai how to test that a method is called inside a then or catch callback

我试图测试这样的事情:

// component.js
import React from 'react';
import AsyncModule from '../some/async/module';
import { doSomething } from '../myModule';

.
.
.

const onSubmit = () => {
  const opts = {/* some config */};

  AsyncModule(opts).someAsyncCall().then(resolved => {
    doSomething();
  }).catch(e => {
    // also
    doSomething();
  });
}

class MyCompontent extends React.Component {

  render() {
    return <Formik onSubmit={onSubmit} ... />;
  }

}

我需要测试正在调用doSomething 到目前为止,我已经编写了一些测试,并且尝试了一些东西,但都没有奏效。 我需要你的帮助:

.
.
.
  it.only('should doSomething on Formik submit when AsyncModule.someAsyncCall promise resolves', () => {
    spyDoSomething = spy(myModule, 'doSomething');
    const expectedResponse = {};
    const stubSomeAsyncCall = stub(AsyncModule, 'someAsyncCall');
    stubSomeAsyncCall.resolves(expectedResponse);
    wrapper = mount(<MyCompontent />);
    const formik = wrapper.find('Formik');

    formik.simulate('submit');

    return expect(spyDoSomething).to.has.been.called;
  });

这个测试显然没有通过。 如何检查then的主体中是否正在调用doSomethingcatch回调?

我正在运行节点 9.1.0、mocha、chai、酶和 sinon。

使用玩笑

import AsyncModule from '../some/async/module';
import { doSomething } from '../myModule';

jest.mock('../myModule');
jest.mock('../some/async/module', () => ({
  someAsyncCall: jest.fn()
}));

it('should doSomething on Formik submit when AsyncModule.someAsyncCall promise resolves', () => {
    const expectedResponse = {};

    AsyncModule.stubSomeAsyncCall.mockReturnValue(expectedResponse);
    wrapper = mount(<MyCompontent />);
    const formik = wrapper.find('Formik');

    formik.simulate('submit');

    expect(doSomething).to.has.been.called;
  });


使用代理查询

it('should doSomething on Formik submit when AsyncModule.someAsyncCall promise resolves', () => {
    const expectedResponse = {};
    const spyDoSomething = sinon.spy();

    proxyquire('../myModule', {
      doSomething: spyDoSomething
    });
    proxyquire('../some/async/module', {
      someAsyncCall: sinon.stub().returns(expectedResponse)
    });


    wrapper = mount(<MyCompontent />);
    const formik = wrapper.find('Formik');

    formik.simulate('submit');

    return expect(spyDoSomething).to.has.been.called;
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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