使用正确的类型模拟带有Jest和Typescript的Express Request [英] Mocking Express Request with Jest and Typescript using correct types

查看:136
本文介绍了使用正确的类型模拟带有Jest和Typescript的Express Request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Jest运行正确的Express Request类型时遇到了一些麻烦.我通过以下代码进行了简单的用户注册:

I have been having some trouble getting the correct Express Request type working in Jest. I have a simple user registration passing with this code:

import { userRegister } from '../../controllers/user';
import { Request, Response, NextFunction } from 'express';

describe('User Registration', () => {
  test('User has an invalid first name', async () => {
    const mockRequest: any = {
      body: {
        firstName: 'J',
        lastName: 'Doe',
        email: 'jdoe@abc123.com',
        password: 'Abcd1234',
        passwordConfirm: 'Abcd1234',
        company: 'ABC Inc.',
      },
    };

    const mockResponse: any = {
      json: jest.fn(),
      status: jest.fn(),
    };

    const mockNext: NextFunction = jest.fn();

    await userRegister(mockRequest, mockResponse, mockNext);

    expect(mockNext).toHaveBeenCalledTimes(1);
    expect(mockNext).toHaveBeenCalledWith(
      new Error('First name must be between 2 and 50 characters')
    );
  });
});

但是,如果我更改:

    const mockRequest: any = {
      body: {
        firstName: 'J',
        lastName: 'Doe',
        email: 'jdoe@abc123.com',
        password: 'Abcd1234',
        passwordConfirm: 'Abcd1234',
        company: 'ABC Inc.',
      },
    };

收件人:

const mockRequest: Partial<Request> = {
  body: {
    firstName: 'J',
    lastName: 'Doe',
    email: 'jdoe@abc123.com',
    password: 'Abcd1234',
    passwordConfirm: 'Abcd1234',
    company: 'ABC Inc.',
  },
};

来自TypeScript文档( https://www.typescriptlang.org /docs/handbook/utility-types.html#partialt ),这应将Request对象上的所有字段设为可选.

From the TypeScript documentation (https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt), this should make all fields on the Request object optional.

但是,出现此错误:

Argument of type 'Partial<Request>' is not assignable to parameter of type 'Request'.
  Property '[Symbol.asyncIterator]' is missing in type 'Partial<Request>' but required in type 'Request'.ts(2345)
stream.d.ts(101, 13): '[Symbol.asyncIterator]' is declared here.

我希望具有TypeScript经验的人可以发表评论,并让我知道我做错了.

I was hoping that someone with a little more TypeScript experience could comment and let me know what I am doing wrong.

推荐答案

您的模拟数据类型不必完全适合实际数据. 嗯,这不是定义.只是一个模拟,对吧?

Your mock data type doesn't have to perfectly fit the actual data. Well, it doesn't by definition. It's just a mock, right?

您需要的是类型声明.这是一种告诉TypeScript 好的,兄弟,我知道我在这里做什么." .

What you need is a type assertion. It's a way to tell TypeScript "Okay bro, I know what I'm doing here.".

这不是生产代码,而是测试.您甚至可能在监视模式下运行它.我们可以在这里毫无疑问地拒绝某些类型的安全性. TypeScript不知道它是模拟的,但是我们知道.

This is not a production code, it's a test. You're probably even running it in watch mode. We can reject some type safety here without problem. TypeScript doesn't know it's a mock, but we do.

const mockRequest = {
    body: {
    firstName: 'J',
    lastName: 'Doe',
    email: 'jdoe@abc123.com',
    password: 'Abcd1234',
    passwordConfirm: 'Abcd1234',
    company: 'ABC Inc.',
    },
} as Request;

如果在测试过程中由于mockRequest与请求不够相似而导致崩溃,我们将知道并修复该模拟,并添加一些新属性等.

If something crashes during the test, because mockRequest isn't similar to Request enough, we'll know and we'll fix the mock, add some new properties etc.

如果as Request不起作用,您可以通过先声明为anyunknown然后再声明为您的类型来告诉TypeScript 我真的知道我在这里做什么" 需要.看起来像

If as Request doesn't work you can tell TypeScript "I REALLY know what I'm doing here" by asserting to any or unknown first and then to the type you need. It would look like

const x: number = "not a number :wink:" as any as number;

当我们想测试我们的代码在输入错误的情况下不能很好地工作时,这很有用.

It's useful when we'd like to test that our code doesn't work well with bad input.

对于您的特殊情况-模拟快递请求-有 jest-express 可以提供帮助您,如果可以的话,当然可以节省node_modules的大小.

For your particular case -- mocking express Request -- there is jest-express to help you, if you can spare the node_modules size of course.

这篇关于使用正确的类型模拟带有Jest和Typescript的Express Request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆