执行前摩卡beforeEach vs [英] Mocha beforeEach vs before execution

查看:118
本文介绍了执行前摩卡beforeEach vs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了一个问题,我无法解释。我在这些测试中有很多代码,所以我要尽力捕捉这个想法。



我的测试看起来像:

  describe('main page',function(){
beforeEach(function(done){
addUserToMongoDb(done) /#1
});

afterEach(function(done){
removeUserFromMongoDb(done);
});

上下文('login',function(){
it('应该记录用户,function(){
logUserIn(user_email); //#2 - 此行要求用户从beforeEach


$ b上下文('preferences',function(){
before(function(done){//#3
logUserInBeforeTest (user_email);
});

它应该显示偏好',function(){
doCheckPreferences(); //#4
}) ;
});
});

问题是,beforeEach由#1 #2 pass中的测试。



然而, #4 的偏好上下文失败,因为它无法找到用户以#3 登录。



似乎在之前的上下文在describe beforeEach ,导致它们失败。如果我将 logUserIn 移动到块,它可以正常工作。


解决方案

摩卡的测试运动员在查看摩卡测试运动员的部分



从Hooks部分:

  describe('hooks',function(){

before(function(){
//在所有测试之前运行块
});

after(function(){
//在此块中的所有测试后运行
});

beforeEach(function(){
//在此块中的每个测试之前运行
});

afterEach(function(){
//每次测试后运行在这个块
});

//测试用例
});

您可以将这些例程嵌套在还可以具有之前/ beforeEach例程的其他描述块中。 >

I ran into a problem recently that I can't explain. I have alot of code in these tests so I'm going to do my best to capture the idea here

I have tests that look like:

describe('main page', function(){
  beforeEach(function(done){
    addUserToMongoDb(done);   // #1
  });

  afterEach(function(done){
    removeUserFromMongoDb(done);
  });

  context('login', function(){
     it('should log the user in, function(){
       logUserIn(user_email);  // #2 - This line requires the user from the beforeEach
     });
  });

  context('preferences', function(){
    before(function(done){    //#3
       logUserInBeforeTest(user_email);
     });

    it('should show the preferences', function(){
       doCheckPreferences(); // #4
    });
  });
});

The problem is, the beforeEach by #1 runs fine. I can see it happening on the DB and the tests in #2 pass.

However, the tests in the preferences context at #4 fail because it cant find the user to log them in at #3.

It seems that the context before is executed before the describe beforeEach, which causes them to fail. If I move logUserIn into the it block it works fine.

What could cause this?

解决方案

Mocha's test runner explains this functionality the best in the Hooks section of the Mocha Test Runner.

From the Hooks section:

describe('hooks', function() {

    before(function() {
        // runs before all tests in this block
    });

    after(function() {
        // runs after all tests in this block
    });

    beforeEach(function() {
        // runs before each test in this block
    });

    afterEach(function() {
        // runs after each test in this block
    });

    // test cases
});

You can nest these routines within other describe blocks which can also have before/beforeEach routines.

这篇关于执行前摩卡beforeEach vs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆