๐ ๋ฌธ์ ์ํฉ
๋ก๊ทธ์์ ํจ์์ ๋ํ ํ ์คํธ ์ฝ๋๋ฅผ ์ง๋ ๋์ค ์๋ ์๋ฌ์ ๋ง์ฃผํ๋ค.
Argument of type OOO is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
์๋ ํ ์คํธํ๋ ค๋ logout ํจ์๋ ์๋์ ๊ฐ์ด ์๊ฒผ๋ค.
///authService.ts
const logout = async (req: Request, res: Response) => {
req.logout(() => {
req.session.destroy(() => {
success(res, statusCode.OK, responseMessage.SUCCESS, {
session: req.session,
});
});
});
};
๊ทธ๋ฆฌ๊ณ ํ ์คํธ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ๋ค.
//authService.test.ts
describe('[authService] logout ํ
์คํธ', () => {
const res = {
status: jest.fn(() => res),
send: jest.fn(),
};
const req = {
logout: jest.fn(() => {
req.session.destroy();
}),
session: {
destroy: jest.fn().mockImplementation(() => {
success(res, statusCode.OK, responseMessage.SUCCESS, {});
}),
},
};
(util.success as any) = jest.fn();
const success = util.success;
test('๋ก๊ทธ์์ ํ
์คํธ', async () => {
await logout(req, res); //์๋ฌ ๋ฐ์
expect(success).toBeCalledWith(
res,
statusCode.OK,
responseMessage.SUCCESS,
{},
);
});
});
authService.ts์ req: Request๋ถ๋ถ์ req๋ก ๋ฐ๊ฟ์ฃผ๋ ์๋ฌ๊ฐ ๋์ง ์์๋ค. ํ์ง๋ง ์ด๊ฑด ํ์ ์คํฌ๋ฆฝํธ์ ํน์ฑ์ธ๋ฐ ํ ์คํธ์ฝ๋๋ฅผ ์ํด ์ง์ฐ๊ณ ์ถ์ง ์์๋ค.
๊ตฌ๊ธ๋ง์ ํด๋ณด๋ Request๋ ๋ชจํนํ๋ ค๋ฉด ์๋ง์ property๋ค์ ๋ชจํนํด์ค์ผํ๋ค๊ณ ํ๋ค. ๊ทธ๋ฐ๋ฐ ๋๋ Request์ ๋ชจ๋ property๋ฅผ ๋ชจํนํด์ฃผ์ง ์์ ์๋ฌ๊ฐ ๋ฐ์ํ๋ ๊ฒ์ด์๋ค.
๐ก ํด๊ฒฐ ๋ฐฉ์
์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์๋ req๋ฅผ any๋ก ์ ์ธํด์ฃผ๋ฉด ๋๋ค. ์๋์ ๊ฐ์ด ๋ง์ด๋ค.
//authService.test.ts
describe('[authService] logout ํ
์คํธ', () => {
const res = {
status: jest.fn(() => res),
send: jest.fn(),
};
const req: any = { //๋ฐ๋ ๋ถ๋ถ
logout: jest.fn(() => {
req.session.destroy();
}),
session: {
destroy: jest.fn().mockImplementation(() => {
success(res, statusCode.OK, responseMessage.SUCCESS, {});
}),
},
};
(util.success as any) = jest.fn();
const success = util.success;
test('๋ก๊ทธ์์ ํ
์คํธ', async () => {
await logout(req, res);
expect(success).toBeCalledWith(
res,
statusCode.OK,
responseMessage.SUCCESS,
{},
);
});
});
์์ ๊ฐ์ด ๋ฐ๊พธ๋ฉด ํ ์คํธ๊ฐ ์ ํต๊ณผ๋๋ค!
๐ Reference
https://goonerholic.github.io/express-testing
๋๊ธ