Search code examples
javascriptsinon

Sinon mock expectation: check function argument object field string using regex?


Hi I want to check the passed argument of a function using a regex. Case is I want to verify an object that contains a generated string that have a random character in some part

this is the string to check

- apple<randomchar>
- banana <randomchar>
- melon <randomchar>

above text is generated, may change between run.

I tried using this sinon.match, but can't found the detailed documentation, so not sure if it's correct way to do this.

const sinon = require('sinon');

const foobar = {
    foo: () => {},
    fooWithObject: () => {},
};
const sinonMock = sinon.mock(foobar);

const textfoobar = (
`- apple randomid
- banana randomid
- melon randomid`
);

sinonMock
    .expects('foo')
    .withArgs(sinon.match(/apple.*banana.*melon/gms));
sinonMock
    .expects('fooWithObject')
    .withArgs({message: sinon.match(/apple.*banana.*melon/gms)});

// this works
foobar.foo(textfoobar);
// this doesn't
foobar.fooWithObject({message: textfoobar});

sinonMock.verify();

Above result error if I wrap the message inside an object. How can I check argument call object that contain a string using regex?


Solution

  • Turns out, also need to use sinon.mock in the container object. So this works

    sinonMock
        .expects('fooWithObject')
        .withArgs(sinon.match({message: sinon.match(/apple.*banana.*melon/gms)}));