Code Monkey home page Code Monkey logo

jest-mock's Introduction

Jest Mocking

A simple test double's demonstration for async axios mocking using jest we use public api https://jsonplaceholder.typicode.com as dummy data

Steps and Installation

  1. Initialize project folder using create-react-app.
npx create-react-app your-folder-name
  1. Install axios as dependency
npm install --save axios
  1. Install necessary development dependencies for out test suite.
npm install --save-dev enzyme enzyme-adapter-react-16 react-test-renderer
  1. Crate src/components folder inside project application folder and other necessary files.
your-project-name/
	src/
		__tests__/
			User.test.js
		components/
			service
				UserService.js
		UserComponent.js
  1. Paste this example code as follows:

    UserComponent.js

    //UserComponent.js
    import React, { Component } from 'react'
    import UserService from './service/UserService';
    
    class UserComponent extends Component {
    
      constructor(){
        super()
    
        this.state = {
          name : ""
        }
      }
    
      getUser = async() => {
    
        try {
          const response = await UserService.addUser({
            name: "Jino"
          });
          
          this.setState({
            name : response.users.name
          });
    
          console.log(response)
        } catch (e) {
           
          this.setState({
            name : e
          });
        }    
      }
    
      render() {
        return (<div><button onClick={this.getUser}>Add new User</button></div>)
      }
    }
    
    export default UserComponent;
    
    

    UserService.js

    //src/service/UserService.js
    
    import axios from 'axios';
    
    class Users {
      static async addUser(users) {
        const resp =  await axios.post(`https://jsonplaceholder.typicode.com/users/`,{users});
        return resp.data;
      }
    
      static async single(id) {
        const resp = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
        return resp.data;
      }
    }
    
    export default Users;
    

    User.test.js

    //User.test.js
    import axios from 'axios';
    import UserService from './service/UserService';
    
    import { configure } from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
    configure({ adapter: new Adapter() });
    
    jest.mock('axios');
    
    test('Should match: Leanne Graham', async(done) => {
       axios.get.mockResolvedValue({data: {name: "Leanne Graham"}});
       const r = await UserService.single(1)
        
       expect(r.name).toEqual("Leanne Graham")
       console.log(r.name)
       done()
    });
    
    
  2. Run you code using jest. npm test

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.