gpt4 book ai didi

javascript - 如何在 Express router Jest 测试中模拟方法?

转载 作者:行者123 更新时间:2023-12-02 21:15:04 26 4
gpt4 key购买 nike

我正在尝试使用 Jest + Supertest 在 Node.js 应用程序中测试路由器,但我的路由器正在调用服务,该服务正在调用端点:

router.post('/login', async (req, res, next) => {
try {
const { username, password } = req.body;

// I WANT TO MOCK userService.getUserInfo FUNCTION, BECAUSE IT IS MAKING A POST CALL
const identity = await userService.getUserInfo(username, password);

if (!identity.authenticated) {
return res.json({});
}

const requiredTenantId = process.env.TENANT_ID;
const tenant = identity.tenants.find(it => it.id === requiredTenantId);

if (requiredTenantId && !tenant) {
return res.json({});
}

const userResponse = {
...identity,
token: jwt.sign(identity, envVars.getVar(envVars.variables.AUTH_TOKEN_SECRET), {
expiresIn: '2h',
}),
};

return res.json(userResponse);
} catch (err) {
return next(err);
}
});

这是我的测试,效果很好:

test('Authorized - respond with user object', async () => {
const response = await request(app)
.post('/api/user/login')
.send(users.authorized);
expect(response.body).toHaveProperty('authenticated', true);
});

这是getUserInfo函数的样子:

const getUserInfo = async (username, password) => {
const identity = await axios.post('/user', {username, password});

return identity;
}

但它在路由器内执行方法getUserInfo,并且此方法正在进行 REST 调用 - 我想模拟此方法以避免对其他服务的 REST 调用。怎么办呢?

我在 Jest 文档中找到了一个 mockImplementation 函数 https://jestjs.io/docs/en/mock-function-api.html#mockfnmockimplementationfn

但是我如何在 super 测试中模拟 func 呢?

最佳答案

您可以在测试顶部使用 jest 的自动模拟

像这样:

jest.mock('./path/to/userService');

// and include it as well in your test
const userService = require('./path/to/userService');

它将生成整个模块的模拟,并且每个函数都将被替换为 jest.fn() 且没有实现

然后根据 userService 如果它只是一个对象,它的 getUserInfo 方法将是一个 jest.fn() 并且您可以像这样设置它的返回值:

// resolved value as it should return a promise
userService.getUserInfo.mockResolvedValue(mockIdentity);

mockIdentity 必须看起来像这样:

const mockIdentity = {
authenticated: true,
tenants: [
{
id: "x12",
mockInfo: "mock-info-value"
}
],
mother: "Superwoman",
father: "Superman"
})
}

关于javascript - 如何在 Express router Jest 测试中模拟方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60994312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com