dimanche 24 février 2019

Сannot set a property in a test

I run the test gives an error:

TypeError: Cannot set property 'background' of undefined

   6 | componentDidMount() {
   7 |     const element = ReactDOM.findDOMNode(this)
>  8 |     element.style.background = 'grey'
     |     ^
   9 |   }

code component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'

class Link extends Component {

  componentDidMount() {
    const element = ReactDOM.findDOMNode(this)
    element.style.background = 'grey'
  }
  render() {
    return (
      <div className="Link">
        test link
      </div>
    );
  }
}

export default Link;

code tests:

import React from 'react';
import Link from './Link';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link />)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

This is a fairly simple component, and as I understand the jest cannot reach the DOM, how do I fix this problem? The simplest thing is that I thought of doing this as:

element.style && (element.style.background = 'gray')

Aucun commentaire:

Enregistrer un commentaire