你可以使用
spyOn
与
mockImplementation
下面是一个工作示例:
// ---- somewhere.js ----
const promiseFunction = () => {
return Promise.resolve({name: 'name from promiseFunction'});
}
export default promiseFunction;
// ---- myclass.js ----
import * as React from 'react';
import promiseFunction from './somewhere';
export class MyClass extends React.Component {
doSomething = () => {
// return the Promise so the test can wait for it
return promiseFunction()
.then((data) => {
this.setState({...this.state, name: data.name});
}).catch(() => {
this.setState({...this.state, error: 'error'});
});
}
render() {
return <div>This is MyClass</div>;
}
}
// ---- myclass.test.js ----
import { shallow } from 'enzyme';
import * as React from 'react';
import { MyClass } from './myclass';
import * as somewhere from './somewhere';
describe('MyClass', () => {
it('sets error in state when promiseFunction rejects', async () => {
// set up mock for promiseFunction
const mock = jest.spyOn(somewhere, 'default');
mock.mockImplementation(() => Promise.reject());
const wrapper = shallow(<MyClass />);
await wrapper.instance().doSomething();
expect(wrapper.state().error).toEqual('error');
// restore promiseFunction
mock.mockRestore();
});
});