i18n and Mocha test cases

250 views
Skip to first unread message

guptan...@gmail.com

unread,
Jun 20, 2016, 5:25:51 PM6/20/16
to Mocha
I am getting following error while running a mocha test cases for a component. It is failing because it is calling this.i18n.t('actual_value');. Beuase it is not able to find i18n for this component. I starting i18n service in test helper. So it should be able to find it. But It is not finding it.Any idea ?
Thanks

TypeError: Cannot read property 't' of undefined

Vlad GURDIGA

unread,
Jun 21, 2016, 1:58:58 AM6/21/16
to Mocha
Hey Guptan!

Could you please share more of you test source code? 8-)

You’re right, from the error message it seems like this.i18n is undefined. One case where it trips me off from time to time is when I set something in a global beforeEach block (as is frequently done in helpers), and then in particular tests I try to use that thing in a before block. And this doesn’t work because any before block is executed before all the beforeEach block, no matter the nesting level.

Here is a quick sample test that demonstrates this:

    ~/tmp/mocha ɀ  cat test/a.js 
var assert = require('assert');
beforeEach(function() {
  console.log('global each');
  this.each = true;
});
describe('a test suite', function() {
  var all, each;
  before(function() {
    all = this;
    this.all = true;
    console.log('* this.each is ', this.each);
  });
  beforeEach(function() {
    console.log('local each, this.all is ', this.all);
  });
  it('runs!', function() {
    assert(this.each, 'this.each is set')
    assert(this.all, 'this.all is set')
  });
});
    ~/tmp/mocha ɀ  mocha test/a.js 

  a test suite
* this.each is  undefined
global each
local each, this.all is  true
    ✓ runs!

  1 passing (18ms)
    ~/tmp/mocha ɀ  


So if this.i18n is set by a test helper in a (possibly global) beforeEach block, and you’re trying to get ahold of it later in a before block, it will not be there. 8-|

Christopher Hiller

unread,
Jul 6, 2016, 6:21:28 PM7/6/16
to Mocha
I would recommend avoiding adding properties to the context object and use the function scope instead, if possible.

// using context
describe('my thing', function () {
  beforeEach(function () {
    this.foo = 'bar';
  });
  it('should blah', function () {
    expect(this.foo + 'baz').to.equal('barbaz');
  });
});

/////////////

// using function scope
describe('my thing', function () {
  let foo;
  beforeEach(function () {
    foo = 'bar';
  });
  it('should blah', function () {
    expect(foo + 'baz').to.equal('barbaz');
  });
});

--
You received this message because you are subscribed to the Google Groups "Mocha" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mochajs+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Reply all
Reply to author
Forward
0 new messages