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();
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With