Javascript 如何从Cypress test调用第三方站点以获取验证码图像的文本?

Javascript 如何从Cypress test调用第三方站点以获取验证码图像的文本?,javascript,cypress,Javascript,Cypress,我需要得到一个“验证码”图像的文本,计算它,并在提交表单时在文本字段中输入值。我发现有一个第三方图书馆可以做到这一点。我的问题是如何在Cypress测试中调用第三方库()?或者是否有其他简单的方法可以使用javascript获取验证码图像,请有人建议如何实现这一点 describe('Check the submission of form', function() { it.only('Verify the submission of form', function() {

我需要得到一个“验证码”图像的文本,计算它,并在提交表单时在文本字段中输入值。我发现有一个第三方图书馆可以做到这一点。我的问题是如何在Cypress测试中调用第三方库()?或者是否有其他简单的方法可以使用javascript获取验证码图像,请有人建议如何实现这一点

describe('Check the submission of form', function() {
      it.only('Verify the submission of form', function() {
        const getCaptcha = () => {      
            // How to call the third party url here or some where ???
            return text  // these text retured are numbers and this look like '35+12 =?'
          }
         cy.visit("testUrl")
         cy.wrap({ name: getCaptcha })   
         cy.get('input[name="textinput1"]').type('Mazda')
         cy.get('input[name="textinput2"]').clear().type('Axela')
         ....// rest of the code 
      })
    })

如果我理解正确,您希望访问您控制的使用captcha的站点,获取捕获图像,然后将其发送给第三方API以解析captcha,然后继续登录该站点

您可以使用调用第三方API:

cy.request('POST', 'http://somesite', body).then((response) => {
    // do something with response.body
})
要从登录屏幕获取验证码图像,您可以使用以下方法:

describe('my website', () => {
    it('should accept typing after login', () => {
        cy.visit('testURL')
        cy.get('a selector to target your #captcha img').then((captchaImg) => {
            // Now you will have the captcha image itself
            const body = { captchaImg } // prepare the body to send to the 3rd party API
            cy.request('POST', 'http://somesite', body).then((response) => {
                // Process the response to extract the field that you are interested in
                // For instance, you could pull out the string '55+20='
                let captchaText = getCaptchaText(response.body)
                let captchaAnswer = getCaptchaAnswer(captchaText)
                cy.get('captcha text input field').type(captchaAnswer)
                // You will probably need to click a submit button

                // Test the site here, now that you have logged in
                cy.get('input[name="textinput1"]').type('Mazda')
                // assert something
                cy.get('input[name="textinput2"]').clear().type('Axela')
                // assert something else     
            })
        })
    })
})
每次测试都执行这个额外的请求将大大降低您的测试速度。因此,最好只测试一次登录流,然后尝试一些替代方法,在其余的测试中绕过站点的登录流。至少,您可以尝试将与验证码相关的测试逻辑放入before钩子中,然后运行一套测试


Cypress建议您不要在测试中访问第三方站点,原因如下所示。他们还建议不要使用你无法控制的测试站点。但是访问第三方API可以通过
cy来完成。request

将尝试这样做,并告知您我在这一步中遇到了错误…键入(response.body.text)
CypressError:cy.type()只能接受字符串或数字。您传入:“未定义”
。即使我得到这样的文本“55+20=?”,我如何计算总和并传递到验证码文本字段?您需要解析响应正文以获得验证码问题-您应该发布一个单独的问题,其中包含响应正文的详细信息。然后你需要解决这个问题。如果它是一个字符串,您需要解析它,然后安全地执行它。同样,您应该在另一个问题中发布返回字符串的详细信息。