Skip to content

test attribute of d3 node with enzyme

han edited this page Nov 28, 2019 · 1 revision

Unit Testing React, D3 with Enzyme and Jest - Medium

enzyme 사용 시 d3 node 의 attribute Test 예시

샘플 코드

import React, { configure } from 'react';

import { shallow, mount } from 'enzyme';
import * as d3 from 'd3'

const { JSDOM } = require('jsdom');

const fakeDom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
global.window = fakeDom.window;
global.document = fakeDom.window.document;

let body = d3.select(fakeDom.window.document).select('body');

const wrapper = mount(<Tag />)
// render() jsx code 를 html 로 변환하다
body.html(wrapper.render().html())

it('attr 접근', () => {
  // 하나인 경우
  console.log(body.select('#one').attr('height'))

  // 두개 이상한 경우
  body.selectAll('rect').each(function() {
    console.log(d3.select(this).attr('height'))
    // getBoundingClientRect 값처럼 html 이 브라우져에서 랜더링 된 후 가져오는 값들은
    // { bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }
    console.log(d3.select(this).node().getBoundingClientRect())
  })
})

selector 결과가 하나인 경우

body.select('#one').attr('height')

selector 결과가 두개 이상인 경우 this 를 사용하기 위해 arrow function 은 사용하지 않는다

body.selectAll('rect').each(function() {
  d3.select(this).attr('height')
})

안 되는 점 아래 코드는 처럼 브라주여에서 랜더링 시 배치되는 것의 값은 가져 올 수 없다

body.select('#one').node().getBoundingClientRect())
# 반환 값 { bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }

Clone this wiki locally