Node js中路由器下的Mock功能。

问题描述 投票:0回答:1

请考虑以下情况,但我无法解决。一个类在路由器("")下被调用,我想测试路由器("")的调用和模拟myFunc的结果。我想测试路由器("")的调用和模拟myFunc的结果。

class A {
  myFunc = async () => {
    await ...
    return result
  }
}

Controller file - C:

router.get("/", async (req, res) => {
    var a = new A();

    a.myFunc()
        .then(result => {
            res.json({"message": result});
        }).catch(e => {
            return []
    })
});

C.test.js:

const request = require("supertest");
const app = require("../C");

jest.mock('A');

test("Test route /", async done => {

        const myFuncMock = jest.fn().mockImplementation(() => [...]);
        A.prototype.myFunc = myFuncMock;

        await request(app)
            .get("/")
            .then(res => {
                expect(res.status).toBe(200); // Not asserted
            });
        done()

    });

我无法成功模拟路由器下的函数结果。

node.js express mocking jestjs supertest
1个回答
0
投票

下面是集成测试方案。

app.js:

const express = require('express');
const { Router } = require('express');
const A = require('./a');

const app = express();
const router = Router();

router.get('/', async (req, res) => {
  const a = new A();

  a.myFunc()
    .then((result) => {
      res.json({ message: result });
    })
    .catch((e) => {
      return [];
    });
});

app.use(router);

module.exports = app;

a.js:

class A {
  myFunc = async () => {
    const result = await 'real data';
    return result;
  };
}

module.exports = A;

app.test.js:

const app = require('./app');
const request = require('supertest');
const A = require('./a');

jest.mock('./a', () => {
  const mA = { myFunc: jest.fn() };
  return jest.fn(() => mA);
});

describe('61505692', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });
  it('should pass', () => {
    const mA = new A();
    mA.myFunc.mockResolvedValueOnce('fake result');
    return request(app)
      .get('/')
      .then((res) => {
        expect(res.status).toBe(200);
      });
  });
});

集成测试结果与覆盖率报告。

 PASS  stackoverflow/61505692/app.test.js (11.834s)
  61505692
    ✓ should pass (34ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   92.31 |      100 |      75 |   91.67 |                   
 app.js   |   92.31 |      100 |      75 |   91.67 | 16                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.785s
© www.soinside.com 2019 - 2024. All rights reserved.