繁体   English   中英

SuperTest / JEST ,如何强制或模拟 400 状态代码?

[英]SuperTest / JEST , how to force or mock a 400 status code?

我正在使用 Jest 和 SuperTest 进行单元测试,但我想不出一种方法来强制路由抛出错误。

我附上了我的代码片段:

    const router = require('express').Router();
    const Thoughts = require('../models/thought.model')
    
    router.get('/thoughts', (req,res)=>{
      Thoughts.find().then((thought)=>{
        res.status(200).send({thought})
      }).catch((err)=>{
        res.sendStatus(400).send(err)
      })
    })
   const normRoutes = require('../routes/normRoutes')
   const request = require('supertest');
   const express = require('express');
   const mongoose = require('mongoose')


    const app = express();

    app.use('/api', normRoutes)

    beforeAll(async () => {
        const url = "MONGO_URL"
        await mongoose.connect(url, {    
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true })
      })


    test('GET /api/thoughts --> 400 if error', () => { 
       ## missing logic to force a 400 
        request(app)
        .get('/api/thoughts)
        .expect(400)
        .done()
    })

Mock find Thought模型的方法以在测试中出现错误而拒绝。

首先,在您的测试中导入模型并使用 jest 对其进行自动模拟。

const normRoutes = require('../routes/normRoutes')
const request = require('supertest');
const express = require('express');
const mongoose = require('mongoose');

const Thoughts = require('../models/thought.model');
# This is hoisted so the previous import it a jest mock.
jest.mock('../models/thought.model');

接下来,通过在mockRestore上调用mockRestore ,确保在运行每个测试之前测试使用实际实现。

const app = express();

app.use('/api', normRoutes)

beforeAll(async () => {
    const url = "MONGO_URL"
    await mongoose.connect(url, {    
        useNewUrlParser: true,
        useCreateIndex: true,
        useUnifiedTopology: true })
  })

beforeEach(() => {
  # This restores the mock back to the actual Thoughts model implementation. 
  # This allows for other tests to use the actual implementation.
  # https://jestjs.io/docs/mock-function-api#mockfnmockrestore
  Thoughts.mockRestore();
});

最后,在应该出错的测试中模拟 find 的实现。

test('GET /api/thoughts --> 400 if error', () => { 
   # Thought model find method is mocked to reject with an error.
   Thoughts.mockImplementation(() => ({
     find: jest.fn().mockRejectedValueOnce(
       new Error('Connection Failed or something')
     );
   }));
   
   ## missing logic to force a 400 
    request(app)
    .get('/api/thoughts')
    .expect(400)
    .done();
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM