在一个网站上,我有一个像这样的缓存基础设施:
部署后,我希望收到站点的“新鲜”且未缓存的版本用于我的赛普拉斯测试。我不想清除所有访问者的缓存。我只是希望我的赛普拉斯测试在部署后看到未缓存的版本。
我的想法是为我所有的
cy.visit
和 cy.request
添加一个标头,然后设置我的 Varnish 缓存设置,以查找它。也在 Redis 中处理它。
在 Varnish 和 Redis 中实际执行此“绕过缓存”设置似乎相当麻烦,但可行。如果有人有更好/更简单的方法来做到这一点,我洗耳恭听。
这个问题的核心是:“如何发送包含所有
cy.visit
和 cy.request
的标头,而不必每次都像这样输入(见下文)?
cy.request({
method: 'GET',
url: 'https://example.org',
headers: {
'x-my-custom-header': 'myValue'
}
}).then((response) => {
// ...
});
cy.visit('/', {
headers: {
'x-my-custom-header': 'myValue'
}});
我考虑在此基础上构建自己的自定义命令。但它很快就会变得长尾和笨拙。
我还考虑过,是否可以拦截所有请求并向其添加标头,在我的
beforeEach
中的e2e.js
中。但我无法让它发挥作用。这是我的尝试:
beforeEach(() => {
cy.intercept('*', (req) => {
req.headers['x-foo'] = 'bar';
});
});
测试发出的请求(通过拦截处理)
您没有提到拦截的问题,只是说这是一个。如果管道中还有其他拦截,则
middleware
选项可确保在调用其他拦截之前添加标头。
// you could have a top-level middleware handler that
// sets an auth token on all requests
// but remember setting `middleware: true` will
// cause this to always be called first
cy.intercept('http://api.company.com/',
{ middleware: true }, <-- don't block the intercepts in the tests
(req) => {
req.headers['authorization'] = `token ${token}`
}
)
示例
beforeEach(() => {
cy.intercept('*', { middleware: true }, (req) => {
req.headers['x-nocache'] = '123'
}).as('header-added')
})
it('/todos/1 with additional header', () => {
cy.intercept('https://jsonplaceholder.typicode.com/todos/1')
.as('wait-for-response')
cy.window().then(win => win.fetch('https://jsonplaceholder.typicode.com/todos/1'))
cy.wait('@wait-for-response')
.its('request')
.its('headers')
.its('x-nocache')
.should('eq', '123')
})
it('/todos/2 with additional header', () => {
cy.window().then(win => win.fetch('https://jsonplaceholder.typicode.com/todos/2'))
cy.wait('@header-added')
.its('request')
.its('headers')
.its('x-nocache')
.should('eq', '123')
})
测试发出的请求(未通过拦截处理)
使用自定义命令向所有内容添加标题
cy.request()
Cypress.Commands.overwrite("request", (originalFn, ...args) => {
const {_} = Cypress
const isMethod = (a) => ['GET','POST','PUT','PATCH','DELETE'].includes(a)
let options = { headers: {} }
if (_.isObject(args[0])) {
_.extend(options, args[0])
} else if (args.length === 1) {
options.url = args[0]
} else if (args.length === 2 && isMethod(args[0])) {
options.method = args[0]
options.url = args[1]
} else if (args.length === 2 && _.isObject(args[1])) {
options.url = args[0]
options.body = args[1]
} else if (args.length === 3) {
options.method = args[0]
options.url = args[1]
options.body = args[2]
}
options.headers['x-nocache'] = '123'
return originalFn(options)
})
cy.request('https://jsonplaceholder.typicode.com/todos/3')
.its('requestHeaders').should('have.property', 'x-nocache', '123')
cy.request({url: 'https://jsonplaceholder.typicode.com/todos/3', headers:{'x-other': 'abc'}})
.its('requestHeaders')
.should(requestHeaders => {
expect(requestHeaders['x-nocache']).to.eq('123')
expect(requestHeaders['x-other']).to.eq('abc')
})