[英]mocha/chai how to test that a method is called inside a then or catch callback
Im trying to test something like this:我试图测试这样的事情:
// 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} ... />;
}
}
I need to test that doSomething
is being called.我需要测试正在调用
doSomething
。 So far, I have some tests written, and i've tried some things but none have worked.到目前为止,我已经编写了一些测试,并且尝试了一些东西,但都没有奏效。 I need your help with this:
我需要你的帮助:
.
.
.
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;
});
this test obviously doesn't pass.这个测试显然没有通过。 How can I check that
doSomething
is being called in the body of the then
and catch
callbacks?如何检查
then
的主体中是否正在调用doSomething
并catch
回调?
Im running node 9.1.0, mocha, chai, enzyme and sinon.我正在运行节点 9.1.0、mocha、chai、酶和 sinon。
Using jest使用玩笑
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;
});
Using proxyquire使用代理查询
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.