Test in React

Test in React

2022/03/23 (新增連結)

基本概念

import isItFriday from './friday';


describe('Today is or is not Friday',() => {

test('Sunday is "Nope"', () => {

expect(isItFriday('Sunday')==='Nope');

});

test('Fridat is "TGIF"', () => {

expect(isItFriday('Friday')==='TGIF');

});

});

    • enzyme

      • DOM testing

src/App.js

import React, { Component } from 'react';

//import logo from './logo.svg';

import './App.css';

import Calculator from './Calculator/Calculator';


class App extends Component {

render() {

return (

<div>

<h2>React Calculator</h2>

<Calculator />

</div>

);

}

}


export default App;

src/App.css

.App {

text-align: center;

}


.App-logo {

animation: App-logo-spin infinite 20s linear;

height: 40vmin;

pointer-events: none;

}


.App-header {

background-color: #282c34;

min-height: 100vh;

display: flex;

flex-direction: column;

align-items: center;

justify-content: center;

font-size: calc(10px + 2vmin);

color: white;

}


.App-link {

color: #61dafb;

}


@keyframes App-logo-spin {

from {

transform: rotate(0deg);

}

to {

transform: rotate(360deg);

}

}

src/App.test.js,shallow是只有產生App,而mount則是產生及App所包含的元件。

import React from 'react';

import App from './App';

import {mount, shallow} from 'enzyme'


describe('Calculator component', () => {

it('renders Calculator', () => {

const component = shallow(

<App />

)

expect(component.exists('Calculator')).toBe(true)

})

})


describe('App: ', () => {

const wrapper = mount(<App/>);

it('It shows,"React Calculator"', () => {

expect(wrapper.text()==='React Calculator');

})

});

BDD

TDD

Unit Test

  • Better unit tests for your front-end application

    • The core of the Testing Library is a “DOM testing library”. It means, when you write unit tests using this library, it will not care if the piece of code that you are unit testing is React or Angular component.

Jest

DOM Testing

react-testing-library

Jest + Enzyme

Others