You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Protractor中处理zone-evergreen.js抛出的HTTP 400 Bad Request错误

解决方案

1. 补全所有异步操作的await标记

你当前测试代码里的元素点击、输入操作都是异步API,未加await会导致执行时序混乱,表单还没完成提交逻辑就开始等待toast元素,也会导致全局错误捕获时机和预期不符。修改后的测试代码参考:

it('it should not allow the user to register with same email address', async () => {
  // navigate to registration page by clicking on the "sign up" button
  await element(by.css('a[routerLink="/auth/registration"]')).click();
  await browser.wait(EC.urlContains('http://localhost:4200/auth/registration'))
  expect(await browser.getCurrentUrl()).toEqual('http://localhost:4200/auth/registration');

  // fill up the form again
  await page.getRegisterFullNameInput().sendKeys(accountFullName)
  await page.getRegisterEmailInput().sendKeys(accountEmail)
  await page.getRegisterPasswordInput().sendKeys(accountPassword)
  await page.getRegisterRepeatPasswordInput().sendKeys(accountPassword)
  await page.getTermsAndConditionsCheckBox().click()

  // submit the form
  await page.getRegisterSubmitButton().click()

  // wait for toastr, should throw an error
  await browser.wait(EC.visibilityOf(element(by.css('.toast-message'))));
  expect(await page.getToastrMessage()).toContain('Email already registered')
})

2. 配置Protractor忽略预期的控制台错误

Protractor默认会将浏览器控制台的未捕获严重错误判定为测试失败,你遇到的zone-evergreen.js抛出的400日志属于浏览器默认打印的HTTP请求错误,属于预期内的正常日志,可以在protractor.conf.js中添加配置过滤这类错误:

exports.config = {
  // 保留你原有配置不变,新增以下配置项
  // 忽略未捕获的全局异常,避免预期内的错误导致测试失败
  ignoreUncaughtExceptions: true,

  capabilities: {
    browserName: 'chrome',
    // 配置控制台日志级别,只捕获严重错误
    loggingPrefs: { 'browser': 'SEVERE' },
    'goog:chromeOptions': {
      args: ['--no-sandbox', '--disable-gpu']
    }
  },

  onPrepare: function () {
    // 自定义日志过滤逻辑,只抛出非预期的严重错误
    afterEach(async () => {
      const logs = await browser.manage().logs().get('browser');
      logs.forEach(log => {
        // 跳过预期的注册接口400错误
        if (log.message.includes('POST http://localhost:3000/users/register 400')) {
          return;
        }
        // 其他严重错误正常抛出
        if (log.level.value >= 1000) {
          throw new Error(`未预期的控制台错误:${log.message}`);
        }
      });
    });
  }
}

3. 检查前端代码的请求错误捕获逻辑

从栈追踪可以看到错误最终触发自注册组件的submit方法,需要确保你的前端代码中已经对注册请求做了错误捕获,不要把400错误直接抛到全局zone中,参考示例:

// registration.component.ts 中的提交逻辑
submit() {
  this.userService.register(this.form.value)
    .pipe(
      catchError(err => {
        // 捕获400错误,弹出toast,不要抛出到全局
        this.toastr.error(err.error.message || '注册失败');
        return of(null);
      })
    )
    .subscribe(res => {
      if (res) {
        // 注册成功逻辑
      }
    })
}

4. 测试用例主动捕获预期错误

如果以上配置都不生效,可以在提交操作处主动捕获异常,只抛出非预期的错误:

// 替换原来的提交按钮点击逻辑
try {
  await page.getRegisterSubmitButton().click()
} catch (err) {
  // 只有不是预期的400错误时才抛出,终止测试
  if (!err.message.includes('400 (Bad Request)')) {
    throw err;
  }
}

内容的提问来源于stack exchange,提问作者edrakali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 09:06:03