Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Jest Mock changes to undefined from one line to another

I want to test my AWS Lambda functions written in typescript. The problem is that I'm mocking a service, which initially works fine and has all expected functions, but from one line to the other it turns to undefined, even though in the console.log right before it is defined.

My lambda function:

export const changePassword = LambdaUtils.wrapApiHandler(
async (event: LambdaUtils.APIGatewayProxyEvent, context: Context) => {

    const accessToken = event?.body?.accessToken;
    const previousPassword = event?.body?.previousPassword;
    const proposedPassword = event?.body?.proposedPassword;

    // let authenticationService = Injector.getByName("AuthenticationService"); // I tried mocking this object but given the dependency injection it is always undefined

    //Request
    const authenticationService = new AuthenticationService(); // Here it is perfectly mocked
    console.log("-> authenticationService", authenticationService); // Here it is also defined with all functions
    const response = await authenticationService.changePassword( 
        accessToken,
        previousPassword,
        proposedPassword
    ); //Here authenticationService is undefined

    console.log("response in auth_handler", response);

    
    if (response?.statusCode === 200) {
        return new LambdaUtilities().createHttp200Response(response);
    } 
}

);

My test component:

jest.mock("../../../controllers/auth.service");
const MockedAuthService = AuthenticationService as jest.Mock<AuthenticationService>;

.....

  test(`Test successful response of changePassword Repo function"`, async () => {
    const accessToken = "accessToken";
    const previousPassword = "123456";
    const proposedPassword = "654321";

    const mockAuthService = new MockedAuthService() as jest.Mocked<AuthenticationService>;
    console.log("-> mockAuthService", mockAuthService);

    const event = {
        body: {
            accessToken,
            proposedPassword,
            previousPassword
        }
    };
    const response = await changePassword(event, {}, {});

    console.log("response", response);
    expect(response).not.toBeNull();
});

Here are screenshots from a debug with PyCharm: Here the authenticationService is still defined Here it appears to be undefined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...