cy.intercept 不应用标头

问题描述 投票:0回答:1

我正在使用 cypress 来测试 api,并且我在哈希中有一个 access_token 参数,我需要将其粘贴在所有请求的授权标头中。

在下面的示例中,如果我直接在 request() 调用中使用标头,一切都会完美运行。如果我将其移入拦截器,我会收到 401/未经授权。我做错了什么?

cy.location('hash').then((hash) => {
    // Extract access_token from hash
    const params = new URLSearchParams(hash.replace('#', ''));
    const accessToken = params.get('access_token');
    cy.log(`Adding Authorization header: Bearer ${accessToken}`);

    // Intercept all requests
    cy.intercept('*', (req) => {
      // Add Authorization header
      
      if (accessToken) {
        //req.headers['Authorization'] = `Bearer ${accessToken}`
      }
      req.continue()
    }).as('auth');

    cy.request({
      url: '/v1/me',
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }).then((response) => {
      expect(response.status).to.eq(200)
      expect(response.body).to.have.property('email')
    })
  });
javascript cypress cypress-intercept
1个回答
0
投票

似乎 cy.request 没有被 cy.intercept 拦截,这几乎为零,但你可以包装 fetch ,它由以下处理:

cy.wrap(null).then(async () => {
  const response = await fetch('/v1/me')
  const data = await response.json()
  expect(data).to.have.property('email')
})
© www.soinside.com 2019 - 2024. All rights reserved.