Created
April 1, 2018 09:20
-
-
Save 16Yongjin/73b123b6c198fa77aac5ce798069bd8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const puppeteer = require('puppeteer') | |
| // 유저 id와 쿠키 key로 만든 세션 버퍼 스트링을 리턴하는 함수 | |
| const sessionFactory = require('../factories/sessionFactory') | |
| // 테스트용 유저 생성 | |
| const userFactory = require('../factories/userFactory') | |
| class CustomPage { | |
| // Puppteer 브라우저, 페이지 객체를 커스텀 객체와 같이 사용하게 해주는 프록시 반환 | |
| static async build () { | |
| const browser = await puppeteer.launch({ headless: false }) | |
| const page = await browser.newPage() | |
| const customPage = new CustomPage(page) | |
| // 세 객체를 하나의 객체로 접근 가능하게 함 | |
| return new Proxy(customPage, { | |
| get(target, property) { | |
| return customPage[property] || browser[property] || page[property] | |
| } | |
| }) | |
| } | |
| constructor (page) { this.page = page } | |
| // 브라우저에 세션 쿠키를 넣어서 로그인한것처럼 보이게 하는 메서드 | |
| async login () { | |
| const user = await userFactory() | |
| const { session, sig } = sessionFactory(user) | |
| await this.page.setCookie({ name: 'session', value: session }) | |
| await this.page.setCookie({ name: 'session.sig', value: sig }) | |
| await this.page.goto('localhost:3000/blogs') | |
| await this.page.waitFor('a[href="/auth/logout"]') | |
| } | |
| // 셀렉터 내부 HTML을 반환하는 메서드 | |
| getContentsOf (selector) { return this.page.$eval(selector, el => el.innerHTML) } | |
| // 크로미엄 내부에서 AJAX 요청을 보내는 메서드 | |
| sendRequest (method, path, data) { | |
| return this.page.evaluate((_method, _path, _data) => { | |
| const options = { | |
| method: _method.toUpperCase(), | |
| credentials: 'same-origin', | |
| headers: { 'Content-Type': 'application/json' } | |
| } | |
| if (options.method === 'POST') | |
| options.body = JSON.stringify(_data) | |
| return fetch(_path, options).then(res => res.json()) | |
| }, method, path, data) | |
| } | |
| execRequests (actions = []) { | |
| return Promise.all( | |
| actions.map(({ method, path, data }) => this.sendRequest(method, path, data) ) | |
| ) | |
| } | |
| } | |
| module.exports = CustomPage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment