gpt4 book ai didi

node.js - 如何在超测中模拟中间件?

转载 作者:行者123 更新时间:2023-12-03 12:13:56 25 4
gpt4 key购买 nike

我想测试app.js中的中间件是否叫做。虽然我模拟了模块 work.js ,它仍然运行原始代码。

应用程序.js

const work = require('./work')
const express = require('require')

const app = express()
.use(work)
.use(...)
.get(...)


module.exports = app

工作.js
function work(req, res, next){...}

module.exports = work

应用-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将被调用一次。有什么不对的吗?我应该改变我的测试吗?

最佳答案

下面的例子对我有用:
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% 的单元测试结果:

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

关于node.js - 如何在超测中模拟中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com