-
-
Notifications
You must be signed in to change notification settings - Fork 3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
before/after have wrong "this" scope? #253
Comments
beforeEach/afterEach use "this" as the |
Maybe I'm doing this wrong then. I'm trying to get a setup into place, then run a bunch of tests and have a teardown. Pretty common use-case, right? Part of my setup is a creating a |
well you can do the same thing with closures: describe('something', function(){
var foo;
...before...
foo = stuff
.. blah blah haha which is also helpful for: describe('utils.parseCookie()', function(){
var parse = utils.parseCookie;
it('should do something', function(){
parse(foo)
})
it('should do something', function(){
parse(foo)
})
it('should do something', function(){
parse(foo)
})
}) but this sort of thing would be nice for shared behaviours since they're not lexically scoped |
True, somehow that escaped me, late night :) Thanks. |
Right - that's why I didn't originally click with closures: I got async tests that need async setup... describe('Async tests', function(){
before(function(done) {
initDb(function(err, conn) {
this.connection = conn;
done()
})
})
describe('Query Database', function() {
before(function(done) {
this.conn.query('select something', done)
})
it('should return results', function(data) {
assert ...
})
}) |
well you can still use enclosed vars for that: describe('something', function(){
var connection;
before(function(done){
initwhatever(function(err, conn){
connection = conn;
done();
...
}) ^ is effectively identical |
https://github.com/visionmedia/mocha/wiki/Shared-Behaviours is the only reason we need "this" as anything special |
Thanks TJ |
Thanks, the only way is reference by the chain testing, it -> it -> it, thats not preaty nice this.test.parent.parent |
Maybe creating a simple Object for the main ñcontext testing var Test = {
connection: null
};
beforeEach(function () {
this.connection = new MongoDbConn();
}.bind(Test));
describe('something', function(){
it('do a query', function(done){
initwhatever(function(err, conn){
this.connection.query('select something', done);
done();
}.bind(Test));
});
}); |
My recommendation is to use closures instead of assigning things to |
beforeEach/afterEach correctly invoke with "this" set to the scope of the suite. before/after however use global object instead. Maybe I'm missing something, but it seems weird why this would be intentional.
Test case:
Result:
The text was updated successfully, but these errors were encountered: