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

问题描述 投票:0回答:2

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

我们的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中间件?

javascript node.js mocha sinon
2个回答
0
投票

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

let sandbox;

beforeEach(() => {
  sandbox = sinon.sandbox.create();

  isAuthenticated = sandbox.stub(authCheck, 'isAuthenticated');
});


afterEach(() => {
  sandbox.restore();
});

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

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

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

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

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


0
投票

我有同样的问题并尝试了这个解决方案没有成功。但是删除require.cache [require.resolve('../../ lib / index.js')]给了我一个想法。我能够使用decache而不是delete require。这解决了我的问题。

const decache = require('decache');


decache('../../lib/index.js');
© www.soinside.com 2019 - 2024. All rights reserved.