Search code examples
typescriptmockingmocha.jssinon

Mock function in typescript


I have the following code to mock:

const P = {
    scripts: {
        getScripts: (name?: any) => {
            // do some stuff and return json
            return { foo: 'value'};
        }
    }
}
export default P;

The code I need to test:

export const getScripts = (name?: string) => {
   return P.scripts.getScripts(name); // I want a mock being called here
};

I manage to use sinonJS for my tests:

const fakeGetScript = sinon.fake.returns({
    foo: 'fakeValue'
});

but I can't figure how to replace the original getScript of P with my fake.

Any idea?


Solution

  • Proxyquire is nice, but it doesn't maintain your typescript types. ts-mock-imports (which I created) is a library that is specifically designed for replacing imports with fakes and it is built on top of sinon. It is also type safe.