WEB/Typescript

[Typescript] Argument of type OOO is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. ์—๋Ÿฌ ํ•ด๊ฒฐ

kite707 2023. 5. 7.

๐Ÿ“Œ ๋ฌธ์ œ ์ƒํ™ฉ

๋กœ๊ทธ์•„์›ƒ ํ•จ์ˆ˜์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋ฅผ ์งœ๋˜ ๋„์ค‘ ์•„๋ž˜ ์—๋Ÿฌ์™€ ๋งˆ์ฃผํ–ˆ๋‹ค.

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

 

Express ์œ ๋‹› ํ…Œ์ŠคํŠธ ์ž‘์„ฑํ•˜๊ธฐ

Express ๋ฐฑ์—”๋“œ์˜ ์œ ๋‹›ํ…Œ์ŠคํŠธ ์‚ฝ์งˆ๊ธฐ

goonerholic.github.io

 

๋Œ“๊ธ€