【问题标题】:Mock function under router in Node jsNode js中路由器下的模拟功能
【发布时间】:2020-08-13 18:30:37
【问题描述】:

请考虑以下情况,但我无法解决。在路由器(“/”)下调用一个类。我想测试路由器(“/”)调用并模拟 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 mocking jestjs integration-testing supertest


    【解决方案1】:

    这里是集成测试解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      相关资源
      最近更新 更多