Cypress: возвращаемое значение пользовательской команды Cypress фактически возвращает ноль в тестовом файле - PullRequest
0 голосов
/ 09 января 2020

Я создал пользовательскую команду Cypress, которая отображает значение с помощью console.log (так что я знаю, что он работает). Однако, когда я вызываю пользовательскую команду в моем тестовом файле Cypress, она возвращает пустое / пустое значение.

поддержка / команды. js:

Cypress.Commands.add('scanAWSDb', (siteId) => {
 let siteName = null //default it to null
 ... some AWS SDK function which scans the DB and check for corresponding Name of the ID: 12345 ...
 siteName = <new value>
 console.log("Value returned is: " + siteName //This displays the value in the web console for the corresponding ID: 12345, let's say name is Taylor
 return siteName //Expected to return "Taylor" in the test file
})

gration / test1.spe c. js:

describe('Display value from the Custom command that scanned the AWS DB', ()=> {
    it('Display value from the Custom command that scanned the AWS DB', () => {
        const siteId = "12345" 
        cy.scanAWSDb(siteId)
            .then((returned_value) => {
                cy.log(returned_value) //This displays a null value so it is not picking up the return value from the custom command which is supposedly Taylor
            })
    })
})

=== Обновление:

Это сработало, но при попытке сделать утверждение, он не работает, поскольку я не могу преобразовать Обещание объекта в строку .

export const scanTable = async (tableName, recordId) => {
    const params = {
        TableName: tableName,
        FilterExpression: '#Id = :RecordId',
        ExpressionAttributeNames: {
            '#Id': 'Id',
        },
        ExpressionAttributeValues: {
            ':RecordId': recordId 
        }
    };

    let scanResults = []; 
    let items
    let index = 0
    do{
        items =  await docClient.scan(params).promise()
        items.Items.forEach((item) => scanResults.push(item))
        params.ExclusiveStartKey  = items.LastEvaluatedKey
        let scannedRecordId = JSON.stringify(items.Items[index].Id)
        cy.log('Record successfully found in table: ' + scannedRecordId )
        index += 1 
    }while(typeof items.LastEvaluatedKey != "undefined")

    return scannedRecordId;
};

Cypress.Commands.add('scanDB', (tableName, recordId, cb) => {
    const record = scanTable(tableName, recordId)
    cb(record) // Callback function
})

Тестовый файл:

const tableName = 'table1';
let recordId = '';

cy.scanDB(tableName, recordId, $returnValue => {
cy.log($returnValue) //<-- THIS DISPLAYS THE OBJECT BUT I NEED TO CONVERT IT TO STRING SO I CAN DO ASSERTION like this:
//expect($returnValue).to.eq(recordId)
    })

===

Обновление № 2: отображает возвращенное значение, но не выбрано для утверждения

aws. js файл:

const AWS = require('aws-sdk')
const region = Cypress.env('aws_region')
const accessKeyId = Cypress.env('aws_access_key_id')
const secretAccessKey = Cypress.env('aws_secret_access_key')
const sessionToken = Cypress.env('aws_session_token')

let scannedRecordId = ''

AWS.config.update({region: region})
AWS.config.credentials = new AWS.Credentials(accessKeyId, secretAccessKey, sessionToken)

const docClient = new AWS.DynamoDB.DocumentClient();

export const scanTable = async (tableName, recordId) => {
    const params = {
        TableName: tableName,
        FilterExpression: '#Id = :RecordId',
        ExpressionAttributeNames: {
            '#Id': 'RecordId',
        },
        ExpressionAttributeValues: {
            ':RecordId': recordId // Check if Id is stored in DB
        }
    };

    let scanResults = []; 
    let items
    let index = 0
    do{
        items =  await docClient.scan(params).promise()
        items.Items.forEach((item) => scanResults.push(item))
        params.ExclusiveStartKey  = items.LastEvaluatedKey
        scannedRecordId = JSON.stringify(items.Items[index].Id)
        cy.log('Record successfully found in table: ' + scannedRecordId)
        index += 1 // This may not be required as the assumption is that only a unique record is found
    }while(typeof items.LastEvaluatedKey != "undefined")

    return scannedRecordId;
};

Cypress.Commands.add('scanDB', (tableName, recordId, cb) => {
    const record = scanTable(tableName, recordId)
    cb(record) // Callback function

    // const record = scanTable(tableName, recordId).then(record => { cb(record) }) //This does not work and returns a console error
})

awsTest. js файл:

const tableName = 'random-dynamodb-table'
let myId = '12345'
it('Verify if ID is stored in AWS DynamoDB', () => {
cy.scanDB(tableName, myId, $returnValue => {
        cy.log($returnValue)
        cy.log(`Record ID: ${myId} is found in table: ` + $returnValue)
        expect($returnValue).to.deep.eq(myId) //This asserts that the Id is found
        })
    })

1 Ответ

0 голосов
/ 05 марта 2020

Если эта AWS функция асинхронная c, вы должны обрабатывать ее как обещание, поэтому вместо этого:

 let siteName = null //default it to null
 ... some AWS SDK function which scans the DB and check for corresponding Name of the ID: 12345 ...
 siteName = <new value>
AWSFunction().then((newValue) => {
  siteName = newValue
  console.log("Value returned is: " + siteName)
  return siteName
});

Также, если в тесте вам нужно только прочитать это значение, вы можете использовать обратный вызов вместо обещания: например,

Cypress.Commands.add('scanAWSDb', (siteId, cb) => {
  AWSFunction().then((newValue) => {
    cb(newValue);
  })
})

// test
cy.scanAWSDb(siteId, (returned_value) => {
  cy.log(returned_value)
});

  • Обновлено:

Для подтверждения строки из объекта вы можете использовать wrap и invoke методы кипариса: документы

scan функция asyn c, поэтому вы должны вызывать ее так:

Cypress.Commands.add('scanDB', (tableName, recordId, cb) => {
    const record = scanTable(tableName, recordId).then(record => { cb(record) };
})

...