Home:ALL Converter>typescript interface extends mock

typescript interface extends mock

Ask Time:2018-08-14T03:27:00         Author:meteor

Json Formatter

I have a typescript interface cRequest that's being passed as a type in a class method. This interface also extends express Request type. What's the correct way to mock this in jest or typemoq?

import { Request } from 'express';
import { User } from '.';
export interface cRequest extends Request {
    context: {
        ID?: string;
        user?: string;
        nonUser?: string;
    };
    user?: User;
}
export default cRequest;

This is being used in a class method as follows

import { Response } from 'express';
public getData = async (req: cRequest, res: Response) => {}

And if i try to test it as follows it fails

const expRespMock: TypeMoq.IMock<Response> = TypeMoq.Mock.ofType<Response>();
const cReqMock: TypeMoq.IMock<cRequest> = TypeMoq.Mock.ofType<cRequest>();
await classObj.getData(cReqMock, expRespMock);

with the following message

  Argument of type 'IMock<cRequest>' is not assignable to parameter of type 'cRequest'.
  Property 'context' is missing in type 'IMock<cRequest>'.

What's the correct way to inject this interface mock into the method in tests?

Author:meteor,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51829292/typescript-interface-extends-mock
meteor :

I was able to overcome this problem as follows\nconst cRequestStub= <cRequest> {};\n\nAnd also it's now possible to selectively inject params as i need without any errors\nconst cRequestStub= <cRequest> {user: undefined}; or\nconst cRequestStub= <cRequest> {context: {ID: '', user: '', nonUser: ''}};\n\nawait classObj.getData(cRequestStub, expRespMock);\n",
2018-08-13T20:45:33
yy