1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

chai.expectとsinon.assertの使い分け

Last updated at Posted at 2017-02-08

sinonでspy/stub/mock化したメソッドのアサーションはsinon.assertを使ったほうがいいと思う。

index.js
function getIndexPage(req, res) {
  return res.render('index');
}

module.exports = getIndexPage
index.spec.js
it('renders index view', () => {
  const req = {};
  const res = {};
  res.render = sinon.spy();

  getIndexPage(req, res);

  expect(res.render.calledOnce).to.be.true;
  expect(res.render.calledWithExactly('indexx')).to.be.true;  // chai.expect
  sinon.assert.calledWithExactly(res.render, 'indexx');       // sinon.assert
});

chai.expectだと、trueを期待したのにfalseだった、という表示になる。
res.render.calledOnceの検証に失敗したのか、res.render.calledWithExactly('indexx')の検証に失敗したのかがわかりづらい。

AssertionError: expected false to be true
  at Context.it (test/index.spec.js:9:57)  // ここで失敗したテストコードの行番号がわかる

sinon.assertだと、失敗箇所がわかりやすく、実際にどんな引数で呼ばれたかがわかる(実際にはrender('index')で呼ばれた)

 expected render to be called with exact arguments indexx
render(index) at getIndexPage (controllers/index.js:2:14)

2017/02/24追記

sinon-chaiを使うと、sinon.assertをexpectで書ける。
これでexpectとsinon.assertが混在しなくなる。

chai.use(require('sinon-chai'));

...

sinon.assert.calledWithExactly(res.render, 'indexx');         // これを

expect(res.render).to.have.been.calledWithExactly('indexx');  // こうやって書ける
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?