cypress를 이용한 UI 테스트 자동화

2018. 11. 28. 18:31서버 프로그래밍

Vue.js로 만든 웹 클라이언트를 Cypress를 이용하여 UI 자동 테스트를 구현하였다. 기본 제공되는 문서가 잘 만들어져 있어서 다른 레퍼런스는 굳이 필요 없어서 좋다.

visit

https://docs.cypress.io/api/commands/visit.html#Syntax

contains

https://docs.cypress.io/api/commands/contains.html#Syntax

fixture

https://docs.cypress.io/api/commands/fixture.html#Syntax

Best Practices


Cypress를 이용한 파일 업로드 테스트

https://stackoverflow.com/questions/47074225/how-to-test-file-inputs-with-cypress

First scenario (upload_file_to_form_spec.js):

I want to test a UI where a file has to be selected/uploaded before submitting the form. Include the following code in your "commands.js" file within the cypress support folder, so the command cy.upload_file() can be used from any test:
Cypress.Commands.add('upload_file', (fileName, fileType, selector) => {
    cy.get(selector).then(subject => {
        cy.fixture(fileName, 'hex').then((fileHex) => {

            const fileBytes = hexStringToByte(fileHex);
            const testFile = new File([fileBytes], fileName, {
                type: fileType
            });
            const dataTransfer = new DataTransfer()
            const el = subject[0]

            dataTransfer.items.add(testFile)
            el.files = dataTransfer.files
        })
    })
})

// UTILS
function hexStringToByte(str) {
    if (!str) {
        return new Uint8Array();
    }

    var a = [];
    for (var i = 0, len = str.length; i < len; i += 2) {
        a.push(parseInt(str.substr(i, 2), 16));
    }

    return new Uint8Array(a);
}

Then, in case you want to upload an excel file, fill in other inputs and submit the form, the test would be something like this:

describe('Testing the excel form', function () {
    it ('Uploading the right file imports data from the excel successfully', function() {

    const testUrl = 'http://localhost:3000/excel_form';
    const fileName = 'your_file_name.xlsx';
    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    const fileInput = 'input[type=file]';

    cy.visit(testUrl);
    cy.upload_file(fileName, fileType, fileInput);
    cy.get('#other_form_input2').type('input_content2');
    .
    .
    .
    cy.get('button').contains('Submit').click();

    cy.get('.result-dialog').should('contain', 'X elements from the excel where successfully imported');
})


Testing Vue web applications with Vuex data store & REST backend

https://www.cypress.io/blog/2017/11/28/testing-vue-web-application-with-vuex-data-store-and-rest-backend/#Store-testing


Test a Node RESTful API with Mocha and Chai

https://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chai