如何在超级测试中模拟中间件? [英] How to mock a middleware in supertest?
本文介绍了如何在超级测试中模拟中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试app.js
中的中间件是否被调用.尽管我模拟了模块work.js
,它仍然运行原始代码.
I want to test if the middleware in app.js
is called. Although I mock the module work.js
, it still runs the original code.
app.js
const work = require('./work')
const express = require('require')
const app = express()
.use(work)
.use(...)
.get(...)
module.exports = app
work.js
function work(req, res, next){...}
module.exports = work
app-test.js
app-test.js
const supertest = require('supertest')
const app = require('../app')
test('test middleware in app.js', async(done) => {
jest.mock('../work', () => jest.fn((req, res, next) => next()))
const agent = () => supertest(app)
const work = require('../work')
await agent()
.get('/')
.set(...)
expect(work).toHaveBeenCalledTimes(1) // Error
done()
})
我希望work.js
将被调用一次.有什么不对的吗?我应该更改测试吗?
I expect that work.js
will be called once. Is there anything wrong? Should I change my test?
推荐答案
以下示例对我有用:
app.js
:
const work = require('./work');
const express = require('express');
const app = express();
app.use(work).get('/', (req, res) => {
res.sendStatus(200);
});
module.exports = app;
work.js
:
function work(req, res, next) {
next();
}
module.exports = work;
app.spec.js
:
jest.mock('./work', () => jest.fn((req, res, next) => next()));
const supertest = require('supertest');
const app = require('./app');
const work = require('./work');
let agent;
let server;
beforeEach(done => {
server = app.listen(4000, err => {
if (err) return done(err);
agent = supertest(server);
done();
});
});
afterEach(done => {
server && server.close(done);
});
describe('app', () => {
test('test middleware in app.js', async () => {
const response = await agent.get('/');
expect(response.status).toBe(200);
expect(work).toHaveBeenCalledTimes(1);
});
});
单元测试结果覆盖率100%:
Unit test result with 100% coverage:
PASS src/stackoverflow/56014527/app.spec.js
app
✓ test middleware in app.js (90ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
app.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.248s
这里是完整的演示: https://github. com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56014527
这篇关于如何在超级测试中模拟中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文