Zotov
Zotov

Reputation: 81

Create RequestMock with dynamic url (params) Testcafe

I'm trying to test login page of my react app using testcafe. After success login app should fetch user from API (on localhost:5000) and display name & surname on the home page.

Fetching user in my app:

const raw = await axios.get(`http://localhost:5000/api/user/${uid}`);

tests/login.test.ts

// Used to mock POST /login-user
const loginMock = RequestMock()
    .onRequestTo("http://localhost:5000/api/login-user")
    .respond(
        {
            success: true,
            id: "123456789101",
        },
        200,
        { "Access-Control-Allow-Origin": "*" }
    );

// Used to mock GET /user/:id
const getUserMock = RequestMock()
    .onRequestTo("http://localhost:5000/api/user/:id")
    .respond(
        {
            success: true,
            user: {
                name: "John",
                surname: "McBain",
            },
        },
        200,
        { "Access-Control-Allow-Origin": "*" }
    );

test.requestHooks([loginMock, getUserMock])("should login user", async t => {
    /* login user testing*/
    ...

    // Check GET /user
    const UserInfo = await Selector(".auth span");
    await browser
        .expect(await UserInfo.textContent)
        .eql("Account: John McBain"); // Failed here "Account undefined undefined" != "Account John McBain"
});

POST /login-user request is working fine, but GET /user/:id request is failed I think the problem is that I'm incorrectly write dynamic url (/:id/). How can I do it correctly? My express server function for GET /user/:id here:

app.get("/api/user/:id", (req, res) => {
    const userId = req.params.id;
    ...
});

Upvotes: 1

Views: 902

Answers (1)

Vladimir A.
Vladimir A.

Reputation: 2212

In the case of dynamic URLs you should use RegExp instead of string in your RequestMock.onRequestTo method. The result RegExp relates to your id possible symbols, for example:

const mock = RequestMock()
    .onRequestTo(/\/id=[0-9]+$/)
    .respond(/*...*/);

Result:

[respond is replaced by mock]     https://example.com/id=13234
[respond is not replaced by mock] https://example.com/id=23443-wrong-part
[respond is not replaced by mock] https://example.com/id=wrong-non-number-id

Upvotes: 1

Related Questions