使用 supertest 配合 jest 进行接口单元测试

本系列是我的常用 koa 中间件使用笔记,防止忘记使用方法而作记录

 supertest 是一个自动测试 koa、express 框架路由接口的工具,通常用来配合单元测试工具使用,本文使用它配合jest进行单元测试。

 

使用方法

//初始化koa并且绑定3000端口
const Koa = require('koa');
const app = new Koa();
app.listen(3000);


//使用koa router
const Router = require('koa-router');
const router = new Router();
app.use(router.routes());

router.get('/', (ctx, next) => {
    ctx.body = 'welcome supertest'
})

//重点来了!supertest使用
const supertest = require('supertest');
const request = supertest(app.callback());

request.get('/').end((err, data) => {
    if (err) {
        console.log(err);
    }
    console.log(data.text); //输出返回结果
})

 

配合jest使用

关于 jest 使用方法 https://blog.csdn.net/nullccc/article/details/113865977

//app.js
const Koa = require('koa');
const app = new Koa();
app.listen(3000);


//使用koa router
const Router = require('koa-router');
const router = new Router();
app.use(router.routes());

router.get('/', (ctx, next) => {
    ctx.body = 'welcome supertest'
})

module.exports = app;

 

//api.test.js
const supertest = require('supertest');
const app = require('./app');

const request = supertest(app.callback());

test('测试接口',async ()=>{
    let result = await request.get('/');
    expect(result.text).toEqual('welcome supertest')
})


//输出结果
// PASS  ./api.test.js
// √ 测试接口 (36 ms)

// Test Suites: 1 passed, 1 total
// Tests:       1 passed, 1 total
// Snapshots:   0 total
// Time:        5.154 s
// Ran all test suites.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值