cod*_*123 27 mocking promise reactjs jestjs enzyme
import { createUser } from '../services';
...
...
handleFormSubmit = () => {
this.setState({ loading: true });
createUser()
.then(() => {
this.setState({
loading: false,
});
})
.catch(e => {
this.setState({
error: e,
});
});
};
Run Code Online (Sandbox Code Playgroud)
it('rejects...', () => {
const Container = createUserContainer(CreateUser);
const wrapper = shallow(<Container />);
return wrapper.instance().handleFormSubmit()
.catch(e => {
console.log("State: ", wrapper.state());
expect(e).toEqual('error');
});
});
Run Code Online (Sandbox Code Playgroud)
export const createUser = function() {
return new Promise((resolve, reject) => {
reject('error');
});
};
Run Code Online (Sandbox Code Playgroud)
测试确实强制代码进入方法中的捕获。所以状态确实被设置为“错误”。
但是在我的测试中,它没有按照我的预期进行操作,而是在测试状态更改之前等待 Promise 拒绝。我不确定在这里尝试什么,我应该使用 async/await 吗?
所以这是createUser
我想要等待的方法,但我不确定我的实现是否允许这样做。
And*_*iol 20
你应该做这样的事情:
it('rejects...', () => {
const Container = createUserContainer(CreateUser);
const wrapper = shallow(<Container />);
return expect(wrapper.instance().handleFormSubmit()).rejects.toEqual('error');
});
Run Code Online (Sandbox Code Playgroud)
我认为这样更干净。您可以在官方文档中看到这种方法。
Cas*_*son 18
测试失败,因为它不知道主题是异步的。它可以通过使用done
参数或制作测试功能来修复async
。
请注意,还需要设置预期断言的数量,以便即使未采用 catch 分支,测试也会失败。
async
/await
风格:
it('rejects...', async () => {
expect.assertions(1);
const Container = createUserContainer(CreateUser);
const wrapper = shallow(<Container />);
await wrapper.instance().handleFormSubmit()
.catch(e => {
console.log("State: ", wrapper.state());
expect(e).toEqual('error');
});
});
Run Code Online (Sandbox Code Playgroud)
旧样式done
参数:
it('rejects...', done => {
expect.assertions(1);
const Container = createUserContainer(CreateUser);
const wrapper = shallow(<Container />);
wrapper.instance().handleFormSubmit()
.catch(e => {
console.log("State: ", wrapper.state());
expect(e).toEqual('error');
done();
});
});
Run Code Online (Sandbox Code Playgroud)
在您的代码中handleFormSubmit
,函数应该返回 Promise,您可以在测试中等待它。此外,您还需要从成功和错误回调中返回真实数据,以分别解决和拒绝承诺。
handleFormSubmit = () => {
this.setState({ loading: true });
return createUser()
.then(() => {
this.setState({
loading: false,
});
return true;
})
.catch(e => {
this.setState({
error: e,
});
throw e;
});
};
Run Code Online (Sandbox Code Playgroud)
在您的实际代码中,您已在处理程序中捕获了错误catch
,并尝试在测试用例代码中进一步捕获它。因此catch
不能进一步链接,但可以链接then
多次。
作为参考,请参阅 Promise 文档: https://www.peterbe.com/plog/chainable-catches-in-a-promise
归档时间: |
|
查看次数: |
32040 次 |
最近记录: |