如何在超级测试中模拟中间件?

tai*_*hen 6 node.js express supertest jestjs

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

应用程序.js

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

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


module.exports = app
Run Code Online (Sandbox Code Playgroud)

工作.js

function work(req, res, next){...}

module.exports = work
Run Code Online (Sandbox Code Playgroud)

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()
})

Run Code Online (Sandbox Code Playgroud)

我希望这work.js会被调用一次。有什么不对的吗?我应该改变我的测试吗?

sli*_*wp2 8

下面的例子对我有用:

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;
Run Code Online (Sandbox Code Playgroud)

work.js

function work(req, res, next) {
  next();
}

module.exports = work;
Run Code Online (Sandbox Code Playgroud)

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

这是完整的演示:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56014527