简体   繁体   English

Module.exports用于在路径/控制器中进行单元测试

[英]Module.exports for unit-testing inside a route/controller

I'm pretty new to NodeJS and unit testing. 我对NodeJS和单元测试非常陌生。

I use Jest , but it should be the same "issue" with Mocha or Ava , or whatever ...Because my problem seems to be about export / import ... 我使用Jest ,但是它应该与MochaAvawhatever ,因为我的问题似乎与export / import

I have a file learning.js with some functions 我有一个带有某些功能的文件learning.js

// learning.js

function sum(a, b) {
  return a + b
}

const multiply = (a, b) => a * b

module.exports = { sum: sum, multiply: multiply }

...and a some.test.js file: ...和some.test.js文件:

// some.test.js

const { sum, multiply } = require('./learning')
// const { sum, multiply } = require('./another')

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})

test('multiplies 2 x 2 to equal 4', () => {
  expect(multiply(2, 2)).toBe(4)
})

At this point, everything is perfect, my tests run and pass. 至此,一切都完美无缺,我的测试通过了。

However, I've a third file named another.js structured that way (I use express ): 但是,我有一个名为another.js的第三个文件,其结构是这样的(我使用express ):

router.get('/another', async function(req, res) {

  // TESTS
  function sum(a, b) {
    return a + b
  }

  const multiply = (a, b) => a * b

  // DO SOME OTHER STUFF...

  res.status(200).send('ok')
})

module.exports = { sum: sum, multiply: multiply }
//module.exports = router

When I try to run the same tests from some.test.js (changing only the require statement to map to another.js ), I can't make it works. 当我尝试从some.test.js运行相同的测试(仅更改require语句以映射到another.js )时,我无法使其工作。 My tests fail: TypeError multiply is not a function . 我的测试失败: TypeError multiply is not a function

I tried to move export somewhere else, to rename some stuff with dot.notation ... I can't make it work. 我试图将export移到其他地方,用dot.notation重命名某些内容...我无法使其正常工作。

Any clue? 有什么线索吗? Thanks! 谢谢!

You're running into a scope problem -- your sum and multiply are out of scope from module.exports , since you're defining them from within your route handler. 您正在运行到一个范围的问题-你的sum ,并multiply超出范围从module.exports ,因为你从你的路由处理程序中定义它们。

Why not try this: 为什么不试试这个:

Create a new file helpers.js or services.js -- however you'd describe your functions. 创建一个新文件helpers.jsservices.js -但是您将描述其功能。

const sum = (a, b) => a + b
const multiply = (a, b) => a * b

module.exports = { sum, multiply }

Then in your express file: 然后在您的快递文件中:

const helpers = require('./helpers.js')

router.get('/another', (req, res) => {
  helpers.sum(1,2)
  helpers.multiply(3,4)
  res.status(200).send('ok')
})

module.exports = router

Then in your test problem, you can require helpers in the same way and test the functions individually. 然后,在测试问题中,您可以以相同的方式要求helpers并分别测试功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM