Jest.js 无法读取undefined的属性(阅读“homepageHandler”)

06odsfpq  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(177)

我有一个文件controllers/index.js

var indexExports = module.exports = {
  
  homepageHandler: function (req, res) {
    console.log(`index page. Req ${req}`);
    return res.status(200).json({
      "message": "welcome"
    });
  }
}

我正在测试代码

const dotenv = require('dotenv');
const request = require("supertest")
var indexControllerModule = require('../controllers/index');

beforeAll(async () => {
  dotenv.config();
  console.log(`Ensure both Mongo and Express is running before running these tests`);
});

describe("Endpoints are accessible", () => {
    it("GET request for homepage should return 200", async () => {
      const baseURL = process.env.EXPRESS_SERVER_TEST 
      console.log(`base url is ${baseURL}`);
      const req = {};
      const res = {
        status: jest.fn(),
        json: jest.fn(),
      }
      indexControllerModule.indexExports.homepageHandler(req,res)
      .then((result)=>{
        console.log(`result is ${result}`);
        expect(1).toBe(1);
      })
      .catch((error)=>{
        console.log(`error in accessing homepage: ${error}`);
      })
    });  
});

当我使用jest运行测试时,我得到了错误

TypeError: Cannot read properties of undefined (reading 'homepageHandler')

      18 |         json: jest.fn(),
      19 |       }
    > 20 |       indexControllerModule.indexExports.homepageHandler(req,res)
         |                                          ^
      21 |       .then((result)=>{
      22 |         console.log(`result is ${result}`);
      23 |         expect(1).toBe(1);

我做错了什么?

w3nuxt5m

w3nuxt5m1#

你想要indexControllerModule.homepageHandler,而不是indexControllerModule.indexExports.homepageHandler
controllers/index.js中,导出一个没有名称的对象(即导出不知道indexExports)。
你也可以这样做:

module.exports = {
  indexExports: {
  homepageHandler: function (req, res) {
    console.log(`index page. Req ${req}`);
    return res.status(200).json({
      "message": "welcome"
    });
  }
}
}

...然后保持测试代码不变。

相关问题