我一直在尝试为新的反应应用程序编写注册页面的单元测试
但是我对Sinon存根/间谍的概念很新,并且在拦截函数调用和强制解决方面遇到了问题。
这是我的初步测试:
test('Success notification is displayed if all information is valid', () => {
wrapper.setState({ username: 'test', password: 'Test1234!@', confirmPassword: 'Test1234!@' });
const stub = sinon.stub(Register.prototype, 'signUp').resolves('Test');
wrapper.find('#submitRegistration').simulate('click');
});
onClick运行此事件处理程序:(简化)
public onSubmitHandler(e: React.FormEvent) {
// Perform password match check
if (password === confirmPassword) {
this.signUp(this.state.username, password);
} else {
// Set success state
}
} else {
// Set error state
}
}
注册:
public signUp(username: string, password: string) {
// Perform Cognito Signup
return Auth.signUp({
password,
username,
})
.then(() => {
// Set success State
})
.catch((err) => {
// Set error state
});
}
如何拦截对signUp的调用并将其强制执行解析路径,目前由于我没有配置我的AWS Amplify Auth模块,因此每次都会捕获“No userPool”
Jest提供了许多模拟依赖关系的方法,主要有两种风格:
对于您的情况,您还需要处理Promises
,因此,您需要遵循testing async behaviour的建议。
对于你的情况,我假设:
// telling jest to mock the entire module
jest.mock("auth-module", () => ({
// telling jest which method to mock
signUp: ({ password, username }) =>
new Promise((resolve, reject) => {
// setting the test expectations / test data
process.nextTick(
() =>
username === "SuccessUser"
? resolve(userName)
: reject({
error: "failure message"
})
);
})
}));
注意:即使它不会运行,也要添加代码段,因为格式化似乎会被代码块破坏。
通过dubes的回答,我设法得到以下内容:
const signUpSpy = jest.spyOn(Auth, 'signUp').mockImplementation((user, password) => {
return new Promise((res, rej) => {
res();
});
});
而不是直接监视我编写的函数并调用将其移动到Modules函数并从那里解决了承诺!