• Home
  • How to test void method with jest? – JavaScript

How to test void method with jest? – JavaScript

To test a void method with Jest, you can use the expect function to check that the method was called and/or modified the correct values.

Here is an example of how you might test a void method using Jest:

const myObject = {
myMethod: () => {
this.value = 'test';
},
value: ''
};

test('test myMethod', () => {
myObject.myMethod();
expect(myObject.value).toBe('test');
});

In this example, we are testing the myMethod method of the myObject object. This method does not return a value, but it does modify the value property of the object. We use the expect function to check that the value property has been correctly set to ‘test’ after the method is called.

You can also use the jest.fn() function to create a mock function and track whether it has been called. For example:

const myObject = {
myMethod: jest.fn(),
value: ''
};

test('test myMethod', () => {
myObject.myMethod();
expect(myObject.myMethod).toHaveBeenCalled();
});

In this example, we are using jest.fn() to create a mock function for the myMethod method. We can then use the toHaveBeenCalled() matcher to check that the mock function was called during the test.

I hope this helps! Let me know if you have any questions or need further clarification.