使用动态 url (params) Testcafe 创建 RequestMock

Create RequestMock with dynamic url (params) Testcafe

我正在尝试使用 testcafe 测试我的 React 应用程序的登录页面。成功登录后,应用程序应从 API(在 localhost:5000)获取用户并在主页上显示姓名。

正在我的应用中获取用户:

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 请求工作正常,但 GET /user/:id 请求失败 我认为问题在于我错误地编写了 dynamic url (/:id/)。我怎样才能正确地做到这一点? 我的 GET /user/:id 快速服务器功能在这里:

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

对于动态 URL,您应该在 RequestMock.onRequestTo method. The result RegExp relates to your id possible symbols, for example:

中使用 RegExp 而不是 string
const mock = RequestMock()
    .onRequestTo(/\/id=[0-9]+$/)
    .respond(/*...*/);

结果:

[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