简体   繁体   中英

Is there a way to fix this "TypeError: express.json is not a function" when testing Express with Jest?

I am trying to learn how to run Jest tests on express.js, but I am getting this error

TypeError: express.json is not a function

but, if I comment out these 2 lines from the index.js:

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));

then it would work and pass the first 2 tests. How could I fix this error?

Here the index.js

and here the index.test.js

You didn't mock the express.json method.

Eg

index.js :

const express = require('express');
const cors = require('cors');
const app = express();
const corsOptions = {
  origin: true,
};
const PORT = process.env.PORT || 4002;
app.use(cors(corsOptions));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

app.listen(PORT, (err) => {
  if (err) {
    console.log('Rumble in the Bronx! ' + err);
  } else {
    console.log(`👽 <(Communications active at port http://localhost:${PORT}/)`);
  }
});

index.test.js :

const express = require('express');

const useSpy = jest.fn();
const listenSpy = jest.fn();
const urlencodedMock = jest.fn();
const jsonMock = jest.fn();

jest.mock('express', () => {
  return () => ({
    listen: listenSpy,
    use: useSpy,
  });
});

express.json = jsonMock;
express.urlencoded = urlencodedMock;

describe('64259504', () => {
  test('should initialize an express server', () => {
    require('./index');
    expect(jsonMock).toBeCalled();
    expect(urlencodedMock).toBeCalled();
    expect(listenSpy).toHaveBeenCalled();
  });

  test('should call listen fn', () => {
    require('./index');
    expect(jsonMock).toBeCalled();
    expect(urlencodedMock).toBeCalled();
    expect(listenSpy).toHaveBeenCalled();
  });
});

unit test result with coverage report:

 PASS  src/stackoverflow/64259504/index.test.js (13.203s)
  64259504
    ✓ should initialize an express server (626ms)
    ✓ should call listen fn (1ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |       75 |       50 |        0 |       75 |                   |
 index.js |       75 |       50 |        0 |       75 |          13,14,16 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        15.01s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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