jest-express / jest-express

Mock Express for testing with Jest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Property 'header' is missing in type 'Request'

daniyel opened this issue · comments

Hi.

This should already be fixed in 1.7.0 version however I am still getting this error with 1.9.0 version.

Issue: #4
Pull: #84

  • express version: 4.16.3
  • jest-express version: 1.9.0
  • node version: 10.9.0
  • npm version: 6.2.0

Relevant code or config

authorization.spec.ts

    import auth from './authorization';
    import { Request } from 'jest-express/lib/request';
  
    test('should let me pass', (done) => {
        propertiesToObject.mockReturnValue({
            'unsecured-default': ['/health'],
            'unsecured-specific': []
        });
        const middleware = auth();
        const next = jest.fn(() => done());
        const req = new Request('/health', {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        middleware(req, null, next);
    });

authorization.ts

  import { Request, Response, NextFunction } from 'express';

  function authMiddleware(req: Request, res: Response, next: NextFunction) {
    ...
  }

What you did:

I have mocked the ExpressJs request and passed it in the middleware function.

What happened:

Error:

src/middleware/authorization.spec.ts:21:20 - error TS2345: Argument of type 'import(".../my-project/node_modules/jest-express/lib/req...' is not assignable to parameter of type 'e.Request'.
      Property 'header' is missing in type 'Request'.

    21         middleware(req, null, next);

Suggested solution:

Add property header in the type Request or even better use express typings.

I will try and dig into this today and get a new release out.

@jameswlane i think the best would be to import express typings and extend those of jest-express, I have tested it manually and I've defined header in the Request, but later I was getting more and more Property 'xyz' is missing in type 'Request' errors.

If you have something working and would like to do a PR I am more than happy to merge it in.

@daniyel Could you link me to the project or an example project that is having this error. So I can work on getting this resolved.

Hi.

Sorry for not coming sooner back with response. Here I managed to make a small repository with same error: https://github.com/daniyel/jest-express-example. At first the tests were passing, which was odd to me, but then later I have installed the "@types/express": "^4.11.1", and then I got the error:

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    src/middleware/authorization.spec.ts:22:16 - error TS2345: Argument of type 'import("/Users/hrvacada/Workspace/test/jest-express-example/node_modules/jest-express/lib/request").Request' is not assignable to parameter of type 'import("/Users/hrvacada/Workspace/test/jest-express-example/node_modules/@types/express/index").Request'.
      Type 'Request' is missing the following properties from type 'Request': header, accepted, param, host, and 44 more.

    22     middleware(req, res, next);
                      ~~~

What I mean by extending typing is, that in typing from jest-express you can import for example express-serve-static-core and implement that and then you can see which properties are missing in your class and add them. For example like:

request.d.ts

/// <reference types="express-serve-static-core" />

import * as core from "express-serve-static-core";

interface IRequestOptions {
    method?: 'GET' | 'POST' | 'DELETE' | 'PATCH' | 'PUT' | 'HEAD' | 'OPTIONS' | 'CONNECT';
    headers?: any;
}
export declare class Request implements core.Request {

...

By this I get in my VS Code error:

Class 'import("/test/jest-express-example/node_modules/jest-express/lib/request").Request' incorrectly implements interface 'import("/test/jest-express-example/node_modules/@types/express-serve-static-core/index").Request'.
  Property 'header' is missing in type 'Request'. [2420]

@daniyel Thank you for the repo, I will try and dig into this as soon as I can. With it being so close to the holidays it maybe a couple weeks.

I have a some thoughts on solutions, but this may be a trial and error sort of thing.

This repo has had a very active community, so maybe someone can pick this up sooner then I can knock it out.

Has any update been made on this?
Still affected by this issue in jest-express 1.9.4

I am will have some free time this week. I will pull down @daniyel example and see if I can get this fixed.

I started working on this issue I feel I have a solid solution to resolve the issue, it will take me a while to test and build this out. I am hoping to have it done by the end of the week.

@jameswlane looking forward to this release. would be great to pass request mock directly to my middlewares that expect a Request from express

I am still working on this, when I built jest-express it was a bare-bones testing utility for my project. Since then it has grown, it seems the underlying issue is I only built out the APIs for ExpressJS and not NodeJS http module that ExpressJS is built on. So I am building out a jest-node-http and jest-express will extend it like ExpressJS extends http. That should allow it to fully match the real interface of an express app. It taking me a bit to dig through all of the NodeJS http code and build a matching interface that will work. Then updatejest-express to extend it. I have about half of it complete already. So I am hoping to have it complete by the end of the month. 🤞

@jameswlane Thank you very much for your work!

I am hoping to start pushing up the new code in a draft PR this week 🤞, if you want to watch the progress:

Team,
I seem to hit a wall, I been stuck on getting past this type error for the last two days. Reaching out to see if someone would like to take a try at it, or at least give me a second pair of eyes.

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    src/middleware/authorization.spec.ts:22:16 - error TS2345: Argument of type 'import("/Users/jameswlane/Projects/GitHub/daniyel/jest-express-example/node_modules/jest-express/lib/request").Request' is not assignable to parameter of type 'import("/Users/jameswlane/Projects/GitHub/daniyel/jest-express-example/node_modules/@types/express/index").Request'.
      Types of property 'app' are incompatible.
        Type 'Express' is not assignable to type 'Application'.
          Type 'Express' provides no match for the signature '(req: Request | IncomingMessage, res: Response | ServerResponse): any'.

    22     middleware(req, res, next);

I am more then happy to push up my spike if someone want's to give it a try. If not I will keep trying to work my way through the issue, but it may take me a little longer than expected.

Hey @jameswlane ,
first of all, i want to thank you for this awesome package! I really like the use of the Request in order to properly mock respective functionality.

However, I recently stumbled upon the same issue as described above. I think it is of utmost important to solve this issue in order to allow a compliant test-scenario..

Is there any new progress on the issue?
Thank you so much for your time and effort!
All the best

@johannesschobel I have currently hit a brick wall on resolving the issue due to it involves not only mocking out Express but the underlying NodeJS layers.

On top of that, I have been traveling for work (Agile / DevSecOps Coach) since Feb and it will go till May. So most of my free time I have been spending with my wife and daughters.

I plan on jumping back on the issues when this engagement is done in May.

If anyone would like to take a stab at this issue, please do. Pull request are always welcomed.

Has there been any progress/resolution on this? @jameswlane

@muskand I have not had the time to work on this issue due to changes at work and home.

This is open for anyone to jump in and PR's are more welcome to help resolve this, long running issue. So if anyone had some free time to try and tackle this issue, the community and myself would greatly appreciate it.

I personally hit a brick wall trying to resolve it and don't have the time and cycles to try and pick it up and tackle it anytime soon.

Unfortunately, jest-express is virtually unusable with typescript in its current form. I have tried using Partial<> and type assertions in tests but the two just won't play nicely when the express route handlers are explicitly typed as Request, Response and NextFunction.

Is this project still being developed or maintained? Core issues haven't been addressed for almost 2 years (e.g. this issue) and there hasn't been a release for well over 12 months.

It's a great idea and a great project but its quickly become unusable and I've resorted to manually mocking my requests and responses.