lundi 19 mars 2018

Mock function not being called in Jest + Enzyme test

I have written a test that mocks the sumbitChoice() function as this function is responsible for an API call. The function is called on clicking the button, '#buttonOption1'.

Currently, the test's assertion fails i.e. 'Expected mock function to have been called.'

App.test.js

import React from 'react';
import App from './App';
import { mount, shallow } from 'enzyme';
import { waitForState } from 'enzyme-async-helpers';

describe('App', () => {

 it('should call the submitChoice method on click' , () => {

  //arrange
    const mockSubmitChoice = jest.fn();
    const app = mount(<App submitChoice={ mockSubmitChoice } />);

  //act
    app.find('#buttonOption1').simulate('click');

  //assert
    expect(mockSubmitChoice).toBeCalled();

  })

})

App.js

import React, { Component } from 'react';

class App extends Component {
  constructor() {
    super();

    this.state =  { imageURLs:  [] }
  }

  componentDidMount() {
    fetch('/comparison')
      .then(res => res.json())
      .then(images => this.setState({
         imageURLs: [...this.state.imageURLs, images]
      }))
      // .bind(this);
      console.log(this.state)
  }

  submitChoice(data) {
    fetch('/comparison', {
      method: 'POST',
      body: JSON.stringify([...this.state.imageURLs, data]),
      headers: new Headers({
        'Content-Type': 'application/json'
      })
    }).then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', response));
  }


  render() {

    return (
      <div className="App">
        <img id='firstImage' className='image' src={this.state.imageURLs[0]} />
        <img id='secondImage' className='image' src={this.state.imageURLs[1]} />
        <button id='buttonOption1' className='button' onClick={this.submitChoice(this.state.imageURLs[0])}>Select Option 1</button>
      </div>
    );
  }
 }

export default App;

Aucun commentaire:

Enregistrer un commentaire