代码之家  ›  专栏  ›  技术社区  ›  Akxe

Cypress仅将我们的域列入白名单

  •  0
  • Akxe  · 技术社区  · 6 年前

    我有一个页面,里面有广告,有时,在iframe里,有时没有。

    这可能不是100%准确的测试方法,但对于我们的案例来说已经足够了。

    我在beforeach中尝试过使用它(不是最佳的,但是如果它可以工作,我会将它变成一个命令并使用它)

    cy.server({
        whitelist(xhr) {
            //  Basicly, does it match any of whitelisted URLs?
            console.log('whitelisting', xhr.url)
            const url = new URL(xhr.url);
            const URLwhitelist: string[] = Cypress.env('URLwhitelist');
            if (!URLwhitelist.length) {
                return true
            }
            return URLwhitelist.some(allowerdUrl => {
                if (allowerdUrl.split('.').length == 2) {
                    return url.host.includes(allowerdUrl);
                } else if (allowerdUrl.startsWith('*.')) {
                    allowerdUrl = allowerdUrl.slice(1);
                    return url.host.includes(allowerdUrl);
                }
    
                throw new Error(`Unparsable whitelist URL (${allowerdUrl})`);
            });
        }
    });
    

    我也发现了一些黑名单的选择 cypress.json ,但我需要白名单而不是黑名单。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Phillipe Bojorquez    6 年前

    Cypress有一个默认的白名单,可以在这里找到信息: https://docs.cypress.io/api/commands/server.html#Options

    更改默认白名单

    sy.server()附带了一个白名单函数,默认情况下可以过滤 输出对静态资产(如.html、.js、.jsx和.js)的所有请求 .css。

    任何通过白名单的请求都将被忽略-不会被忽略 也不会以任何方式将其存根(即使它与 特定路径()。

    通过Ajax获取。

    Cypress中的默认白名单函数是:

    const whitelist = (xhr) => {
    // this function receives the xhr object in question and
    // will whitelist if it's a GET that appears to be a static resource
    return xhr.method === 'GET' && /\.(jsx?|html|css)(\?.*)?$/.test(xhr.url)
    }
    

    cy.server({
    whitelist: (xhr) => {
    // specify your own function that should return
    // truthy if you want this xhr to be ignored,
    // not logged, and not stubbed.
    }
    })
    

    似乎可以通过在cypress.server上设置选项来永久覆盖该白名单: https://docs.cypress.io/api/cypress-api/cypress-server.html#Syntax