几个小时以来,我一直在尝试用Jest、Supertest和Express测试我的rest api的一个endpoint。
此endpoint受名为“adancedAuthGuard
”的身份验证中间件保护。
所以我试图模拟这个中间件,以便跳过endpoint测试的身份验证检查
//./router.js
router.get('/route1', advancedAuthGuard(false), controller);
重要事项:< code>advancedAuthGuard是一个接受配置参数的中间件(curried middleware)
//./middleware/advancedAuthGuard.js
const advancedAuthGuard = (additionalCondition) => (req,res,next) => {
//Check authentication logic ...
const isAuth = true
if (isAuth && !additionalCondition)
next()
else
next(new Error('Please auth'))
}
当我运行以下测试以检查我是否收到状态代码“200”时。测试在运行前失败。
//./test.js
import supertest from "supertest"
import app from './app.js'
import { advancedAuthGuard } from "./middlewares/advancedAuthGuard";
jest.mock("./middlewares/advancedAuthGuard")
const request = supertest(app)
beforeEach(()=>{
jest.clearAllMocks()
})
it("should '/route1' respond with 200 status", async ()=>{
const mockedMiddleware = jest.fn().mockImplementation((res, req, next)=> next() )
advancedAuthGuard.mockReturnValue(mockedMiddleware)
const res = await request.get("/route1")
expect(res.status).toEqual(200)
})
我得到以下错误:
Test suite failed to run
Route.get() requires a callback function but got a [object Undefined]
> 10 | router.get('/route1', advancedAuthGuard(false), controller);
| ^
因此,我推断问题来自模拟...
当我通过控制台.log调试它时,我意识到我得到了一个不完整的模拟:
advancedAuthGuard(false)
)是否存在我还注意到:
所以我想知道为什么我不可能用Jest和Supertest模拟Expressjsendpoint中使用的通用中间件(带参数的中间件)。
这里有一个github链接,带有最小的express、jest和supertest配置,您可以通过运行test.js
文件来重现这个问题。https://github.com/enzo-cora/jest-mock-middleware
不知道为什么它没有按照您尝试的方式工作,但如果您将模拟实现传递给 autoMock 函数,它将解决问题。
import supertest from "supertest";
import app from "./app";
jest.mock("./middlewares/simpleAuthGuard", () => ({
simpleAuthGuard: (_, __, next) => next()
}));
jest.mock("./middlewares/advancedAuthGuard", () => ({
advancedAuthGuard: () => (_, __, next) => next()
}));
const request = supertest(app);
describe('My tests', () => {
beforeEach(() => jest.clearAllMocks());
it("should '/route1' with advanced middleware work", async () => {
const res = await request.get("/route1");
expect(res.status).toEqual(200);
});
it("should '/route2' with simple middleware work", async () => {
const res = await request.get("/route2")
expect(res.status).toEqual(200)
});
});