I am working with Typescript and Jest to try to test some components for my Angular and Ionic application, but the issue is not limited to Angular or Ionic. As such, I am trying to get the mock functionality of Jest to work.
I am simply creating a dummy class that I want to try to mock the responses of functions to see if I can override the behaviour.
jest-mock.ts
export class AClass {
constructor() { }
GetOne():any {
return 1;
}
GetTwo():any {
return 2;
}
}
jest-mock.spec.ts
import { AClass } from './jest-mock';
// const mockGet = jest.fn( () => { return 3; } ); // Tried this to return 3?
const mockGet = jest.fn();
jest.mock('./jest-mock', () => {
return jest.fn().mockImplementation( () => {
return { GetOne: mockGet };
});
});
describe('Testing Jest Mock is working', () => {
it('should support mocking out the component', () => {
expect(mockGet).toBeTruthy();
expect(mockGet).toBe(3); // Mocked Value
});
});
I am simply trying to create a test that can change the result of the function, so that my mock will be used by other real test code to provide results for testing.
When I try to create a class from the mock TestObject = new AClass();
TypeError: _jestMock.AClass is not a constructor
With the test defined above, I get the following error:
expect(received).toBe(expected)
Expected value to be (using Object.is):
3
Received:
[Function mockConstructor]
Difference:
Comparing two different types of values. Expected number but received function.
While checking other references, I did manage to get the mock test working. I changed the jest-mocks.spec.ts to be:
jest.mock('./jest-mock', () => {
return { // Define Function Mock Return Values
GetOne: jest.fn( () => 3 )
}
});
const MockObject = require('./jest-mock');
describe('mock function', () => {
it('should create mock', () => {
expect(jest.isMockFunction(MockObject.GetOne)).toBeTruthy();
});
it('should return mock values', () => {
expect(MockObject.GetOne()).toBe(3);
expect(MockObject.GetOne).toHaveBeenCalled();
expect(MockObject.GetTwo).toBeUndefined();
});
});
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