导入函数上的jest Mock实现

eaf3rand  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(214)

我正在尝试为typescript服务器端点编写jest测试。我有一个功能文件,我的服务器用来验证和处理后端数据。我想模拟这些函数,以便它们根据测试返回不同的值。然而,我的身体 post 请求从未传递到服务器,所有值都未定义,因此它不会测试基本操作。我是否正确地模拟了这些函数?为什么我的测试后不发送 val1 , val2val3 正确地 apiEndpoints ? 我在运行测试时记录它们,它们总是 undefined .

//server.ts
import * as dotenv from "dotenv";
dotenv.config();

import * as express from "express";
import * as bodyParser from "body-parser";
import * as compression from "compression";
import * as cors from "cors";
import * as morgan from "morgan";
import * as apiEndpoints from "./apiEndpoints";

// instantiate express
const app = express();
const PRODUCTION = process.env.NODE_ENV === "production";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(compression());
app.use(cors());
app.use(express.static("./dist/client"));
app.use(morgan("short"));

/**A closure over a response that can handle an error */
const catchError = (res: express.Response) => {
    return;
};

// ------------------- apiEndpoints -------------------------
apiEndpoints.addRoutes(app);

// ------------------- start server -------------------------
const serverPort = process.env.PORT || 3000;
app.listen(serverPort);

export default app;
export { app };
//apiEndpoints.ts
import * as express from "express";
import { accessLogger } from "./logging/appLogger";
import * as helperFunctions from "./helperFunctions";

function addRoutes(app: express.Express) {
    app.use(accessLogger);

    app.post("/my-endpoint", (req, res) => {
        const { val1, val2, val3 } = req.body;

        if (!val1 || !val2 || !val3) {
            res.status(422).json({message: 'Invalid request'});
            return;
          }

        const res1 = helperFunctions.func1();
        if(!res1){
            res.status(400).json({ Error: "helper function 1 failed" });
            return;
        }

        const res2 = helperFunctions.fun2();
        if(!res2){
            res.status(400).json({ Error: "helper function 2 failed" });
            return;
        }

        res.status(200).json({ status: "ok" });
    });
}
export { addRoutes };
//helperFunctions.ts

async function function1() {
    try {
        //do Something
    } catch (error) {
        return false;
    }
    return true;
}

async function function2() {
    try {
        //do Something
    } catch (error) {
        return false;
    }
    return true;
}

export { function1, function2 };
//apiEndpoints.spec.js
import * as apiEndpoints from "../../src/server/apiEndpoints";
import request from 'supertest';
import express from "express";
import * as bodyParser from "body-parser";
import {function1, function2} from '../../src/server/helperFunctions'

jest.mock('../../src/server/helperFunctions', () => ({
    function1: jest.fn(),
    function2: jest.fn(),
}));

describe('Test Suite 1', () => {
    let app, test_body;

    beforeAll(() => {
        app = express();
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: false }));
        apiEndpoints.addRoutes(app);

        test_body = {
            body: {
                val1: "one",
                val2: "two",
                val3: true,
            }
        };
    });

    describe('/my-endpoint', () => {
        test('should return 400 status for failed function2', async () => {
            function1.mockImplementation(() => true);
            function2.mockImplementation(() => false);
            let res = await new Promise(next => request(app)
                .post("/endpoint1")
                .send({test_body})
                .end((err, res) => next(res)));
            expect(res.status).toBe(400);
        });

    });
});

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题