Jest Mocks – changing the property of a mock property / function on mocks


Say i want to keep seperation between simple modules in a practice tech test (boris-bikes), by creating a mock of the Bike class, as shown here:

import { bike } from "../__mocks__/bike.mock";
import { Person } from "./../Person";

describe("Person", () => {
  let mockBike = bike();
  let person: Person;

  beforeEach(() => {
    person = new Person();
  });

  it("should be able to report a bike as broken", () => {
    person.reportBroken(mockBike);
    expect(mockBike.working).toBe(false);
  });
});

import { Bike } from "./../Bike";

export const bike = (overwrites?: Partial<Bike>): Bike => ({
  working: true,
  reportBroken: () => { this.working = false },
  ...overwrites,
});

I want to implement the reportBroken function on the bike mock – so that it changes the working to false… but this is possibly undefined – so how do i change its value? Thanks for your time.

Source: JavaSript – Stack Overflow

October 17, 2021
Category : News
Tags: javascript | jestjs | mocking | typescript | unit testing

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.