小编Bor*_*uhh的帖子

使用正确的类型使用 Jest 和 Typescript 模拟 Express 请求

我在 Jest 中获取正确的 Express Request 类型时遇到了一些麻烦。我有一个使用此代码传递的简单用户注册:

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 …
Run Code Online (Sandbox Code Playgroud)

express typescript jestjs

21
推荐指数
2
解决办法
2万
查看次数

使用 Jest 简单模拟 Passport 功能

我目前正在对我的所有路线进行单元测试,包括一些使用自定义护照身份验证功能的路线。我试图模拟护照功能来测试错误处理,但我不断收到错误:

TypeError: _passport.default.authenticate(...) is not a function
Run Code Online (Sandbox Code Playgroud)

这是运行的实际代码/controllers/users.js

export const persistentLogin = (req, res, next) => {
  // Authenicate the cookie sent on the req object.
  passport.authenticate('jwt', { session: false }, async (authErr, user) => {
    // If there is an system error, send 500 error
    if (authErr) return res.sendStatus(500);

    // If no user is returned, send response showing failure.
    if (!user) {
      return res.status(200).json({
        success: 'false',
      });
    }
  })(req, res, next);
};
Run Code Online (Sandbox Code Playgroud)

这是测试代码/tests/controllers/users.js

import passport …
Run Code Online (Sandbox Code Playgroud)

node.js express jestjs passport.js

6
推荐指数
1
解决办法
1万
查看次数

使用 Jest 模拟 AWS SES

我尝试在 Jest 中模拟 AWS SES,但仍然收到此超时错误:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
Run Code Online (Sandbox Code Playgroud)

我已经删除了不相关且经验证可以正常工作的代码。下面是使用 SES 的代码:

import SES from 'aws-sdk/clients/ses';

try {
    /** Initialize SES Class */
    const ses = new SES({ apiVersion: '2010-12-01' });

    await ses.sendTemplatedEmail(sesEmailParams).promise();
} catch(err) {
    return next(internalErrorMessage);
}
Run Code Online (Sandbox Code Playgroud)

这是使用 SES 的测试:

import AWS from 'aws-sdk';

test('Should error when ses.sendTemplatedEmail.promise() fails', async (done) => {
    const fakeSesPromise …
Run Code Online (Sandbox Code Playgroud)

unit-testing node.js jestjs aws-sdk aws-sdk-nodejs

6
推荐指数
1
解决办法
6281
查看次数