【发布时间】:2018-01-16 20:23:22
【问题描述】:
有没有办法在测试期间选择性地禁用中间件?还是我错过了一个可以帮助我解决问题的基本概念?
背景:我正在编写一些功能测试来记录一个使用 Nodejs 和 Express 的部分编写的网站。到目前为止,我正在使用 selenium-webdriver、Mocha 和 Chai 编写测试。我不反对更改应用程序代码或测试工具。我的问题是如何在测试时使用我的 Google reCAPTCHA?目前它已加载到我的注册表中并使用中间件进行验证。如果 process.env.NODE_ENV 设置为测试,我可以禁用 reCAPTCHA,但我觉得完全禁用它不会测试整个站点。这是一些相关的代码。
控制器:
r.route('/register')
.get(
userController.getReturnURL,
userController.registerForm
)
.post(
userController.validateRegistrationForm,
userController.validateGoogleCaptcha,
catchErrors(userController.insertUser),
catchErrors(userController.sendEmailValidation),
authController.login
);
userController.validateGoogleCaptcha 方法
exports.validateGoogleCaptcha = (req, res, next) => {
const data = {
secret: process.env.RECAPTCHA_SITE_KEY,
response: req.body['g-recaptcha-response'],
};
axios({
method: 'post',
url: `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${req.body['g-recaptcha-response']}`,
data: data,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
req.body.captchaSuccess = response.data.success;
next();
})
.catch(function (response) {
req.flash('error','Sorry! There was an error on our side in confirming your humanity with Google\'s reCAPTCHA service. Please try again, if you continue to have problems please <a href="/contact">contact us</a>.');
// register form takes advantage of Google's reCAPTCHA and we need to load the script in the <head> element.
req.body.jsScripts = ['https://www.google.com/recaptcha/api.js'];
return res.render('user/registrationForm', {title: 'Register your Personal Account', body: req.body, flashes: req.flash()});
});
};
到目前为止我的功能注册测试
const ...
describe('Registration Page', () => {
var server, driver;
const port = 8888,
domain = `http://localhost:${port}`;
before(() => {
server = app.listen(port);
driver = new webDriver.Builder()
.forBrowser('firefox')
.build();
});
after((done) => {
server.close(done);
driver.quit();
});
it('Should Render the Registration Page', async () => {
await driver.get(domain);
await driver.findElement(By.linkText('Register')).click();
const title = await driver.findElement(By.css('h1')).getText();
expect(title).to.include('Register');
const formElements = await driver.findElement(By.css('form#registrationForm'))
.findElements(By.css('input'));
expect(formElements).to.have.length(6);
});
});
这些测试的下一步是开始测试有效和无效的提交。有什么建议、帮助或想法吗?谢谢!
【问题讨论】:
标签: node.js selenium express recaptcha functional-testing