简体   繁体   中英

Order of Operations in `before` and `describe` blocks in Mocha/Chai Node Tests

To try and understand the execution order of one of my Mocha tests (where I was seeing functions execute out of order), I created the following simple test case:

describe("methods", function () {
  before(async function () {
    console.log('---------- BEFORE ------------');
    let sum = 1 + 2;
    console.log('sum: ', sum);
  });
  describe("test case", async function () {
    console.log('---------- AFTER ------------');
  });
});

Again, all I wanted to check here was the order of operations. And sure enough, in this case, all that prints to the console is ------------ AFTER ------------ . The logging from the before block doesn't show up in the console at all.

Why is this? What am I missing here?

In my actual test case I use the before block to create and save a document. And then in the next describe block I look it up in the db. When I ran into issues where the document was being looked up before creation had happened I decided to do some simpler tests. Hence what you see above.

it's because of the "before" block is executed just before an IT block

try to execute this:

describe("methods", function () {
  before(async function () {
    console.log('---------- BEFORE ------------');
    let sum = 1 + 2;
    console.log('sum: ', sum);
  });
  it('should be a test', function(){

    console.log('test');

  });
  describe("test case", async function () {
    console.log('---------- AFTER ------------');
  });
});

see this post for more: https://gist.github.com/samwize/8877226

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM