最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何在测试节点API时使用jest(jest.mock())模拟快速会话中间件

运维笔记admin11浏览0评论

如何在测试节点API时使用jest(jest.mock())模拟快速会话中间件

如何在测试节点API时使用jest(jest.mock())模拟快速会话中间件

我正在尝试测试一个端点,准确地说是一个发布请求,以我的测试运行者为笑话,但是我一直收到错误connect ECONNREFUSED 127.0.0.1:80

我已经尝试对使用redis作为存储的express-session进行存根处理,但仍然无法正常工作。这是我的代码

我尝试在测试文件中模拟Express-Session,但失败了,我很确定我没有将options正确传递给函数

user.test.js

const options = {
  secret: process.env.SESSION_SECRET,
  name: '_session',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false },
};

// I tried this
jest.mock('express-session', () => ((options)) => (req, res, next) => {
  next();
});

// I also tried it with no options passed into the mock
// returns TypeError: Class extends value undefined is not a constructor or null at const redisStore = connectRedis(session);

jest.mock('express-session', () => () => (req, res, next) => {
  next();  
});

这是我的发帖请求测试

it('should signup a new user with status 201', async () => {
    const newUser = {
      email: '[email protected]',
      password: 'testing12',
      firstName: 'Tester',
      lastName: 'Woman'
    };
    const res = await agent.post('api/v1/users/signup').send(newUser);
    expect(res.statusCode).toEqual(201);
  });

我希望快速会话可以被模拟,并且测试应该通过,但是我得到了一个错误connect ECONNREFUSED 127.0.0.1:80,并且测试根本没有运行

回答如下:

[我已经看到我的错误,我错过了post('api/v1/users/signup')的斜线,这样就解决了post('/api/v1/users/signup')

发布评论

评论列表(0)

  1. 暂无评论