Can sinon stub withArgs match some but not all arguments

前端 未结 4 1495
慢半拍i
慢半拍i 2021-01-31 13:33

I have a function I am stubbing that gets called with multiple arguments. I want to check just the first argument. The rest are callback function, so I want to

4条回答
  •  有刺的猬
    2021-01-31 13:53

    this method works very well with spies if you want to check only one argument among many

    it('should check only first argument', function ():void {
                myFunction('foo', 'bar', baz');
                expect(myFunctionSpy.firstCall.args[0]).to.equal('foo');
            });
    

    However I don't understand why you are using stubs here. If you just want to check how the function is called you should use a spy. If you want to check how it's called AND change it's behaviour (ex: blocking ajax calls) then you should use a mock.

    Sinon mocks have their own way of checking stuff. The only way I know for your case would be to use sinon.match.many for the arguments you don't want to check:

    it('should check only first argument', async function (): Promise {
                    mock.expects('myFunction').withExactArgs('foo', sinon.match.any, sinon.match.any).returns('foo');
                    await myFunction('foo', 'bar', baz');
                    mock.verify();
                });
    

    mock.verify() will proceed to the test AND reset the mock for other tests, in case of using a spy or a stub you should do it mannually with restore() or reset() after each test

    PD: sorry about TypeScript syntax here :p

提交回复
热议问题