首页 文章

使用Sinon对auth函数进行存根和恢复仍会导致使用存根进行Mocha测试

提问于
浏览
0

我们试图在一些快速应用程序中存在一个身份验证中间件,而不是在我们的所有测试中,我们在为我们制作存根工作时遇到了麻烦 .

我们的mocha测试看起来像这样:describe('primaryDeal routes unit test',()=> {

describe('Authentication allows for data fetching', () => {
        let app;
        let getPrimaryDealData;
        let queryParams;
        let isAuthenticated;    
        let count = 0;

        beforeEach(() => {
            // console.log(isAuthenticated);
            if (count === 0) {
                isAuthenticated = sinon.stub(authCheck, 'isAuthenticated');
                isAuthenticated.callsArg(2);
            }
            app = require('../../lib/index.js');
        });   


        afterEach(() => {
            if (count === 0) {
                isAuthenticated.restore();
            }
            app.close();
            count++;
        });

        it(('should send an API request, validate input and return 200 response'), () => {
            return chai.request(app)
                .get('/api/contracts/')
                .then((res) => {
                    expect(res).to.have.status(200);
                });
        });

        it(('should respond with forbidden'), () => {    

            app = require('../../lib/index.js');    

            return chai.request(app)
                .get('/api/contracts/')
                .catch((res, err) => {
                    expect(res).to.have.status(403);
                });
        });
    });    
});

我们的存根按预期用于第一个 it ,但是存根似乎没有为第二个 it 恢复,并且我们的身份验证中间件没有运行 . 如果另一个被注释掉,两个测试都有效 .

我们已经尝试在不同的文件中分离这些块,并且在不同的 describe 块中,我们也尝试切换 it 块的顺序,我们尝试给两个 chai.request(app) 单独的服务器,但我们不知所措 .

为什么我们的第二个 it 声明不会调用我们的Auth中间件?

1 回答

  • 0

    我建议你使用沙盒 . 它使用起来更优雅 . 无需单独恢复存根 . 这是一个示例:

    let sandbox;
    
    beforeEach(() => {
      sandbox = sinon.sandbox.create();
    
      isAuthenticated = sandbox.stub(authCheck, 'isAuthenticated');
    });
    
    
    afterEach(() => {
      sandbox.restore();
    });
    

    此外,你可以尝试添加替换

    app = require('../../lib/index.js');
    

    delete require.cache[require.resolve('../../lib/index.js')]
    app = require('../../lib/index.js');
    

    另一种想法,也许你需要在这种特殊情况下使用 reset 而不是 restore

    附:也可以看到index.js源代码也很好

相关问题