ts-mockito icon indicating copy to clipboard operation
ts-mockito copied to clipboard

Optional method parameters are no matched with anything()

Open Necroskillz opened this issue 4 years ago • 2 comments

I have a small issue where setups are only match to exact number of parameters. So if there are optional parameters the setup is no matched and I need to create additional setups for each parameter count. It would be nice to have anything match an unspecified parameter, or have some other way to specify that it's optional (so you can have optional string, optional number etc).

class A {
    method(a: string, b?: string) {
        return a + b;
    }
}

describe('test', () => {
    let a: A;

    beforeEach(() => {
        a = mock(A);

        when(a.method(anything(), anything())).thenReturn('a');
        // when(a.method(anything())).thenReturn('a'); <-- this would be needed
    });

    it('should work', () => {
        expect(instance(a).method('x', 'y')).toBe('a'); // ok
        expect(instance(a).method('x')).toBe('a'); // null
    });
});

Necroskillz avatar Jul 06 '20 13:07 Necroskillz

Just ran into this as well

PhakornKiong avatar Feb 03 '23 04:02 PhakornKiong

+1, any updates on this?

fabiosangregorio avatar Jan 25 '24 14:01 fabiosangregorio