Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a method which uses `instanceof ` on a mocked dependency

I have a typeguard which checks the instance of a dependency.

  private isObjectOfA(obj: A | B ): obj is A {
    return obj instanceof A;
  }

In the spec file, I have mocked the class A.

jest.mock('./my-package/a', () => {
  return {
    A: jest.fn().mockImplementation(() => {
      return {
        someMethod: jest.fn()
      };
    })
  };
});

import { A } from './my-package/a';

Now during testing, isObjectOfA always returns false ( because in tests the instance of obj is returned as 'Object' instead of 'A'. Maybe due to the mock ??). Is there anyway to overcome this issue? The code for the object creation looks like,

this.myObj = someCondition ? new A() : new B();
like image 431
JPS Avatar asked Aug 17 '20 14:08

JPS


People also ask

How to test a method in Mockito?

Verify the calls on the mock objects. Mockito keeps track of all the method calls and their parameters to the mock object. You can use the verify() method on the mock object to verify that the specified conditions are met. For example, you can verify that a method has been called with certain parameters.

How to mock method calls in Mockito?

With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of changed state.

What is a mocked instance?

Instance mocking means that a statement like: $obj = new \MyNamespace\Foo; …will actually generate a mock object. This is done by replacing the real class with an instance mock (similar to an alias mock), as with mocking public methods.

How do you check if a method is called in jest?

To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.


1 Answers

In order to pass instanceof check, prototype chain needs to be established, e.g. with Object.create:

jest.mock('./my-package/a', () => {
  const ActualA = jest.requireActual('./my-package/a');

  return {
    A: jest.fn().mockImplementation(() => {
      const a = Object.create(ActualA.prototype);
      return Object.assign(a, { someMethod: jest.fn() });
    })
  };
});

Class auto-mock will provide correct prototype chain for a mock as well.

like image 126
Estus Flask Avatar answered Nov 15 '22 07:11

Estus Flask