Develop Note by J.S.

[Cypress] Api Test 본문

FrontEnd/Cypress

[Cypress] Api Test

js-web 2023. 7. 12. 16:13
반응형

Cypress에서 로그인 버튼 클릭 시 API 요청 및 응답에 대한 E2E TestComponent Test 예제를 작성하였습니다. 

 

1. Cypress API TEST  종류

Cypress의 API TEST는 Spying과 Spying & Stubbing 및 Dynamic Stubbing 이 있습니다.

// spying
cy.intercept('/users/**')
cy.intercept('GET', '/users*')
cy.intercept({
  method: 'GET',
  url: '/users*',
  hostname: 'localhost',
})

// spying and response stubbing
cy.intercept('POST', '/users*', {
  statusCode: 201,
  body: {
    name: 'Peter Pan',
  },
})

// spying, dynamic stubbing, request modification, etc.
cy.intercept('/users*', { hostname: 'localhost' }, (req) => {
  req.reply({ plan: 'starter' }) // 응답 객체 setting
  req.continue((res) => {
  })
})

spying은 api를 단순 감시를 하고, spying & stubbing은 api 의 응답 데이터의 stub을 지정하여 테스트를 수행합니다. 

또한 dynamic stubbing은 request와 response를 지정할 수 있습니다.

 

2. Test Code

1) E2E Test

describe('Login', () => {
  it('should login successfully', () => {
    cy.visit('/login'); // 로그인 페이지로 이동

    // 로그인 폼 채우기
    cy.get('[data-test="username-input"]').type('myusername');
    cy.get('[data-test="password-input"]').type('mypassword');

    // 로그인 버튼 클릭
    cy.get('[data-test="login-button"]').click();

    // API 요청 테스트 
    cy.intercept('POST', '/auth').as('loginRequest');
    // mocking 시에 fixture 필요
    //cy.intercept('POST', '/auth', fixture: "public-transactions.json").as('loginRequest');
    cy.wait('@loginRequest').then((interception) => {
      expect(interception.response.statusCode).to.equal(200);
      expect(interception.response.body).to.have.property('token');
    });
  });
});

응답데이터 수정방법

// response data 수정 방법
cy.intercept("POST", "/auth", (req) => {
  const { body } = req
  req.continue((res) => {
    res.body.data.customList = [1,2,3]
  })
})

2) Component Test

import { mount } from '@cypress/vue';
import Login from '@/components/Login.vue';

describe('Login', () => {
  it('login button is clicked', () => {
    mount(Login);

    cy.get('[data-test="username-input"]').type('myusername');
    cy.get('[data-test="password-input"]').type('mypassword');

    // 로그인 이벤트를 감시하여 처리
    cy.on('login', (username, password) => {
      expect(username).to.equal('myusername');
      expect(password).to.equal('mypassword');
    });

    // 로그인 버튼 클릭
    cy.get('[data-test="login-button"]').click();
  });
});

 

반응형

'FrontEnd > Cypress' 카테고리의 다른 글

[Cypress] Custom Command Test  (0) 2023.07.18
[Cypress] Cypress + MSW  (0) 2023.07.17
[Cypress] Cypress Methods & Assertions정리  (0) 2023.07.12
[Cypress] 선택자 & Custom Command  (0) 2023.07.12
[Cypress] Vite + Cypress  (0) 2023.07.10