我有一个文件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);
我做错了什么?
1条答案
按热度按时间w3nuxt5m1#
你想要
indexControllerModule.homepageHandler
,而不是indexControllerModule.indexExports.homepageHandler
。在
controllers/index.js
中,导出一个没有名称的对象(即导出不知道indexExports
)。你也可以这样做:
...然后保持测试代码不变。