Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Mocking multiple calls

I'm using ts-mock-imports and I want to mock multiple return values of a function call, then check that a function was called a given number of times. The following works:

    const getUserSpy = dataServiceMock.mock('getUserFromDB')
                                      .returns({...USER_1})
                                      .returns({...USER_2});

In my test case, I have two calls to getUserFromDB() and with the above, getUserSpy.callCount is equal to 2. But this is order-dependent, so I'd rather be able to do the following:

    const getUser1Spy = dataServiceMock.mock('getUserFromDB')
                                      .withArgs(USER_1_ID).returns({...USER_1});
    const getUser2Spy = dataServiceMock.mock('getUserFromDB')
                                      .withArgs(USER_2_ID).returns({...USER_2});

What I would expect is that getUser1Spy is called once, and getUser2Spy is called once. However, it looks like the second call to withArgs() removes the previous instance of mocking.


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

1 Answer

0 votes
by (71.8m points)

This worked:

const getUserSpy = dataServiceMock.mock('getUserFromDB');
getUserSpy.withArgs(USER_1_ID).returns({...USER_1});
getUserSpy.withArgs(USER_2_ID).returns({...USER_2});

// ... then ...

assert(getUserSpy.callCount).equals(2);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...