我想驗證來自REST端點的JSON回應,所以我不能使用 "should "方法,因為它針對的是網頁的DOM(我沒有--只有REST API可用)。 我的JSON回應看起來是這樣的:
[
{
"id"。111。
"createdAt": "2021-09-14T16:19:29.803",
"datasetId": "cypress-datasetId2"。
},
{
"id": 112,
"createdAt": "2021-09-14T16:19:29.874",
"datasetId": "cypress-datasetId"。
},
{
"id": 113,
"createdAt": "2021-09-14T16:30:37.101",
"datasetId": "cypress-datasetId3"。
},
]
我事先不知道回應將包含多少個資料集。我也不知道 "id "的計數器。我需要找出回應中是否包含某個datasetId。我的測驗內容是:
it('Validate the datasetId of any entry - expect', () => {
cy.request({
method: 'GET',
url: http://localhost:8040/data-sets',
}).then((response) => {
expect(response.body).to.deep.equal({datasetId: 'cypress-datasetId3'})
})
});
AssertionError出現了:
預期 [ Array(6) ] to深深地等于 { datasetId: 'cypress-datasetId3' }
在代碼位置為。".equal"。 因此,它沒有告訴你結果是什么樣子的,只告訴你它的預期和它出錯了。 我怎樣才能在我得到的任何一個資料集中檢查是否存在某個欄位作為回應?或者是什么讓我能夠識別整個資料集,例如:
。 {
"id": 113,
"createdAt": "2021-09-14T16:30:37.101",
"datasetId": "cypress-datasetId3", "cypress-datasetId3", },
并將其作為結果回傳?
我嘗試的眾多替代方案之一是:
it('Validate the datasetId of any entry - should', () => {
cy.request({
method: 'GET',
url: 'http://localhost:8040/data-sets',
}).its('body').should('deep.contain', {
datasetId: 'cypress-datasetId3')
})
});
其結果是
Timed out retrying after 4000ms: expected [ Array(6) ] to deep include { datasetId: 'cypress-datasetId3' }
資料庫是空的,所以尋求資料集應該不會有延遲。
真正可行的是解決陣列中的特定資料集,但通常我不能提前知道這一點:
it('Validate the datasetId of the first entry - include', () => {
cy.get('@data-sets')
.its('body').its('0').its('datasetId').should('include', 'cypress-datasetId');
});
我怎樣才能使我的方法更通用,并獨立于結果順序呢?
uj5u.com熱心網友回復:
回應是一個陣列,所以你可以.map()到datasetId
cy.request( {
...
}).then((response) => {
const datasetIds = response.map(item => item.datasetId)
expect(datasetIds).to.include('cypress-datasetId3')
})
要獲得整個物件,使用.find()
cy.request( {
...
}).then((response) => {
const found = response.find(item =>/span> item. datasetId === 'cypress-datasetId3')
cy.wrap(found).as('dataset)
})
cy.get('@dataset')
.its('datasetId')
.should('eq', 'cypress-datasetId3')
uj5u.com熱心網友回復:
如果你想斷言陣列的一整個部分,你必須使用deep.include。像這樣:
it("驗證任何條目的datasetId - should", ()=> {
cy.request({
method: "GET"。
url: "http://localhost:8040/data-sets"。
}).then((response) =>/span> {
expect(response.body).to.deep.include({
id: 113,
createdAt: "2021-09-14T16:30:37.101",
datasetId: "cypress-datasetId3"。
})
})
})
或者如果你只是想斷言datasetId的值。為此,首先你必須從json中提取數值到一個陣列中,然后斷言它,類似這樣:
it("驗證任何條目的datasetId - should", ( ) => {
cy.request({
method: "GET"。
url: "http://localhost:8040/data-sets"。
}).then((response) =>/span> {
var datasetIdArray = [] //this will have all the datasetid's for (var index in response.body) {
datasetIdArray.push(response.body[index].datasetId)
}
expect(datasetIdArray).to.include("cypress-datasetId")
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/309932.html
標籤:
