首页 > 解决方案 > 我想将动态 json 主体传递给 cypress request() 函数并定义有效负载值

问题描述

我是柏树的新手,所以如果我在这里没有任何意义,我深表歉意。我有一个执行 POST 请求的柏树脚本。我的最终目标是检查 API 验证。API 是否响应给定 JSON 正文的正确错误消息。为此,我想将具有不同值的相同 JSON 主体传递给 cypress 请求函数。

我在不同的 js 文件中有我的 JSON 对象。(channel_query.js)

export const CreateChannel = {
"name": "channe Name",
"tagline": "tasdsadsaest",
"date": "03 Mar 2021",
"time": "2.00 p.m",
"beginsOn": "2021-03-04T13:59:08.700",
"expiresOn": "2021-05-28T14:54:08.700",
"description": "sample Descritptin",
"url": "www.google.com"}

我在集成文件夹(channel.js)中有我的柏树请求

import { CreateChannel } from '../queries/channel_query';
it('Create a channel',function() {
    cy.request({
        method: 'POST',
        url: '{my URL}',
        body: CreateChannel ,
        headers: headers
        }).then((response) => {
            expect(response.status).to.eq(201)
            expect(response.body.name).to.eq(CreateChannel.name)
    })
}) })

我的问题是,

如何使 JSON 对象中的值动态然后在 cypress 请求函数中定义它们?所以我可以通过相同的 JSON 来检查不同的验证。

@先生。格列布·巴赫穆托夫

非常感谢帮助!

标签: javascriptjsonautomationcypressweb-api-testing

解决方案


最简单的方法可能是在 JSON 文件中放置一组通道并使测试数据驱动。

export const channelData = [
  {
    "name": "channe Name",
    ... // plus other properties
  },
  {
    "name": "name2",
    ... // plus other properties
  },
]

考试

import { channelData } from '../queries/channel_query';

describe('Test all channels', () => {

  channelData.forEach((channel, index) => {

    it(`Testing channel "${channel.name}"`, function() {
      cy.request({
        method: 'POST',
        url: '{my URL}',
        body: channel,
        headers: headers
      }).then((response) => {
        expect(response.status).to.eq(201)
        expect(response.body.name).to.eq(channel.name)
      })
    }) 
  })

推荐阅读