【问题标题】:How to set up 'supertest' to test imported functions?如何设置“supertest”来测试导入的函数?
【发布时间】:2020-06-14 10:42:55
【问题描述】:

与互联网上大多数使用的教程不同

app.post("/login", (req, res) => { ... });

我已经设置了这样的路线

import * as LoginController from './controllers/login/login';

app.post("/login", LoginController.postLogin);

LoginController 中是

export function postLogin(req, res) {
  ...
}

那么,我想知道如何在不从app.js 中获取module.exports = app 的情况下使用supertest 对postLogin(req, res) 进行单元测试?

有没有可能做类似的事情

import request from "supertest";
import { postLogin } from "./login"; // we're in src/controllers/login/login.test.js

describe("POST Login", () => {
    it("should return 200 OK", (done) => {
        request(postLogin)
            // some post data
            .expect(200, done);
    });
});

【问题讨论】:

    标签: javascript node.js express supertest


    【解决方案1】:

    如果您的意图是实际对 postLogin 进行单元测试,您可以模拟 req/res 对象并将它们传递给 postLogin 方法。

    describe("postLogin", () => {
        it("should not reject and return expected data", async () => {
            const reqMock = { path: "somePath", body: {} };
            const resMock = {};
            const result = await postLogin(req, res); // assuming that postLogin returns a promise
            expect(result.someProperty).to.eql(tbd);
        });
    });
    

    如果您的意图是通过超集发出实际请求并验证应用的响应(顺便说一下,这更像是集成测试而不是单元测试),那么除了要求 app.js 并启动之外别无选择你的应用程序。

    【讨论】:

      猜你喜欢
      • 2016-04-29
      • 1970-01-01
      • 2021-09-27
      • 2013-04-30
      • 2021-01-06
      • 2016-12-23
      • 1970-01-01
      • 2018-04-03
      • 2022-01-06
      相关资源
      最近更新 更多