我正在使用 Nodejs 构建一个小库,但在使用 mocha 和 chai 进行单元测试时遇到了一些麻烦。
当我尝试监视一个函数并期望使用某些参数调用它时,就会出现问题。
实际上,当我登录时,传递给函数的参数是好的。但测试一次又一次失败。
这是我正在测试的内容:
import callback from './callback'
/**
* Connect the express routes with the injector directly inside of the app
* @param {Object} app An express application, or an application that has the same api
* @param {Object} injector An injector with the interface of deepin module
* @param {Object} parser An object with the interface of route-parser module
*/
const expressKonnector = (app, injector, parser) => {
const routes = parser.parseRoutes()
for (const route of routes) {
app[route.method](route.pattern, callback(injector, route))
}
}
export default expressKonnector
这是回调依赖模块:
import callbackRender from './callbackRender'
import { HttpRequest } from 'default-http'
export default (injector, route) => {
const ctrl = injector.get(route.controller)
return (request, response) => {
const result = ctrl[route.controllerMethod](new HttpRequest())
if (result.then) {
return result.then(res => callbackRender(res, response))
} else {
callbackRender(result, response)
}
}
}
这是失败的测试:
it('should call the app.get method with pattern /users/:idUser and a callback', () => {
const spy = chai.spy.on(app, 'get')
const routes = routeParser.parseRoutes()
expressKonnector(app, injector, routeParser)
expect(spy).to.have.been.called.with('/users/:idUser', callback(injector, routes[1]))
})
当测试失败时,我有以下堆栈:
ExpressKonnector ExpressKonnector should call the app.get method with pattern /users/:idUser and a callback:
AssertionError: expected { Spy, 3 calls } to have been called with [ '/users/:idUser', [Function] ]
at Context.<anonymous> (C:/Project/javascript/express-konnector/src/test/expressKonnector.spec.js:176:43)
如果您想了解更多详细信息,或者只需运行“npm install && npm test 命令”,您可以在此 github(开发分支)上获取该模块:
最佳答案
callback()
每次都会返回一个新函数,因此它们无法相互比较。
演示:
const giveFunc = () => () => 'bar';
let func1 = giveFunc();
let func2 = giveFunc();
console.log( func1 === func2 ); // false
您可以进行部分匹配,以验证第一个参数:
expect(spy).to.have.been.called.with('/users/:idUser');
如果您确实想要测试正确的函数是否通过,则不能使用匿名函数,因此您必须为其命名:
return function callbackFunc(request, response) {
...
};
您随后必须找到 spy 的函数参数,并根据预期检查其名称:
expect(spy.args[0][1].name).to.equal('callbackFunc');
其中 spy.args[0][1]
表示“第一次调用的第二个参数 ([1]
) ([0 ]
) 到 spy ”,它应该是由 callback()
生成的函数。
由于您的 spy 被调用了三次,您可能需要迭代 spy.args
并检查每个函数参数的正确性。
关于javascript - 带参数的 Mocha 茶单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37874571/