2016-06-17 9 views
0

私はNodejsを使って小さなライブラリを構築しています。私はmochaとchaiでユニットテストをしています。ユニットテスト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 

コールバックに依存するモジュールです:ここで

は、私がテストをM何

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) 

あなたはより詳細な情報を持っている、または単に実行したい場合、あなたはこのgithubの(DEVブランチ)上のモジュールを持つことができ、 "NPM & & NPM testコマンドをインストール":

https://github.com/Skahrz/express-konnector

答えて

1

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.args[0][1]はスパイの最初の呼び出し( [0])について 「第二引数([1])を意味
expect(spy.args[0][1].name).to.equal('callbackFunc'); 

"は、callback()によって生成される関数である必要があります。

あなたのスパイが3回呼び出されるので、おそらくspy.argsを反復して、それぞれの関数の引数が正しいかチェックしてください。

関連する問題