Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

mock an API call in Jest

// index.test.js
const getFirstAlbumTitle = require('./index');
const axios = require('axios');

jest.mock('axios');

it('returns the title of the first album', async () => {
  axios.get.mockResolvedValue({
    data: [
      {
        userId: 1,
        id: 1,
        title: 'My First Album'
      },
      {
        userId: 1,
        id: 2,
        title: 'Album: The Sequel'
      }
    ]
  });

  const title = await getFirstAlbumTitle();
  expect(title).toEqual('My First Album');
});
Comment

jest mock method by name

import Foo from './Foo';
import Bar from './Bar';

jest.mock('./Bar');

describe('Foo', () => {
  it('should return correct foo', () => {
    // As Bar is already mocked,
    // we just need to cast it to jest.Mock (for TypeScript) and mock whatever you want
    (Bar.prototype.runBar as jest.Mock).mockReturnValue('Mocked bar');
    const foo = new Foo();
    expect(foo.runFoo()).toBe('real foo : Mocked bar');
  });
});


Comment

jest mock mockname

test("mockName", () => {
  const mockFn = jest.fn().mockName("mockedFunction");
  mockFn(); // comment me
  expect(mockFn).toHaveBeenCalled();
});
Comment

mock callback function jest

const bodyToAssertAgainst = {};
globals.request.post = jest.fn().mockImplementation((obj, cb) => {
    cb(null, bodyToAssertAgainst);
});
Comment

mock function jest

/*
The Mock Function
The goal for mocking is to replace something we don’t control with something 
we do, so it’s important that what we replace it with has all the features 
we need.

The Mock Function provides features to:

1. Capture calls
2. Set return values
3. Change the implementation

The simplest way to create a Mock Function instance is with jest.fn()
*/

test("returns undefined by default", () => {
  const mock = jest.fn();

  let result = mock("foo");

  expect(result).toBeUndefined();
  expect(mock).toHaveBeenCalled();
  expect(mock).toHaveBeenCalledTimes(1);
  expect(mock).toHaveBeenCalledWith("foo");
});

Comment

jest mock call

test("mock.calls", () => {
  const mockFn = jest.fn();
  mockFn(1, 2);

  expect(mockFn.mock.calls).toEqual([[1, 2]]);
});
Comment

jest mock implementation once

const myMockFn = jest
  .fn()
  .mockImplementationOnce(cb => cb(null, true))
  .mockImplementationOnce(cb => cb(null, false));

myMockFn((err, val) => console.log(val));
// > true

myMockFn((err, val) => console.log(val));
// > false
Comment

jest mock instance

test("mock.instances", () => {
  const mockFn = jest.fn();

  const a = new mockFn();
  const b = new mockFn();

  mockFn.mock.instances[0] === a;
  mockFn.mock.instances[1] === b;
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: random code generator using random alphanumeric string 
Javascript :: javascript tag 
Javascript :: new features of angular 11 
Javascript :: ja display snippet from text string 
Javascript :: onclick remove textarea value 
Javascript :: phaser aseprite animation 
Javascript :: ionic vue use .env 
Javascript :: load all icon from a folder in react 
Javascript :: react native test redux 
Javascript :: Implementing state lifecycle in react class component 
Javascript :: compare if strings are equal javascript 
Javascript :: rest parameters 
Javascript :: prop type for component react js 
Javascript :: crud in nodejs sequilize 
Javascript :: addeventlistener javascript multiple functions 
Javascript :: javascript length of array 
Javascript :: how to get the value of AutoCompelet Component in MUI 
Javascript :: javascript if 
Javascript :: get date in milliseconds javascript 
Javascript :: new date.gettime() is not a constructor 
Javascript :: what is angularjs 
Javascript :: add href to image javascript 
Javascript :: ApolloClient 
Javascript :: jquery validation date min max 
Javascript :: javascript array de imagenes 
Javascript :: remove duplicated from array 
Javascript :: validar correo electronico en js 
Javascript :: what is prototype javascript 
Javascript :: nested array in json 
Javascript :: animated node with tag 1 does not exist 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =