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

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

问题描述

我在 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),这应该使请求对象上的所有字段都是可选的.

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 与 Request 不够相似,我们会知道并且我们将修复模拟,添加一些新属性等.

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 不起作用,您可以通过断言 any 来告诉 TypeScript 我真的知道我在这里做什么"unknown 首先是您需要的类型.它看起来像

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 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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