【问题标题】:What is the correct way of using sinon spy restore or reset?使用 sinon spy restore 或 reset 的正确方法是什么?
【发布时间】:2017-01-07 17:27:22
【问题描述】:

我有 mocha、sinon 和 chai 的测试服:

describe('general visor methods tests', () => {

    let res, req, next, resSpy, resNext;

    beforeEach(() => {
        res = {};
        next = () => {};
        resSpy = res.json = sinon.spy();
        resNext = next = sinon.spy();
    });
    afterEach(() => {
        resSpy.restore();
        resNext.reset();
    });


describe('get basemap layers from owner model', () => {
    it('should send the basemap provided by the owner model', () => {
        owner.basemap = ['basemap1', 'basemap2'];
        getBaseMapLayersFromConfig(req, res, next);
        //  console.log(resSpy.args[0][0].data);
        expect(resSpy.calledOnce).to.eql(true);
        expect(resSpy.args[0][0].message).to.eql('basemaps correctly found');
        expect(resSpy.args[0][0].data).to.eql(['basemap1', 'basemap2']);
    });

...

如果我输入resSpy.reset() 它工作正常。我读过reset()函数是为了重置spy的状态。

但我不明白的是,如果我放 resSpy.restore() 那么它会抛出下一个错误:

TypeError: resSpy.restore is not a function

我不知道我做错了什么,也不知道使用恢复的正确方法是什么。

我也不知道什么时候应该使用重置或恢复。

【问题讨论】:

    标签: javascript unit-testing mocha.js sinon chai


    【解决方案1】:

    spy.restore() 仅在您使用以下初始化时才有用:

    let someSpy = sinon.spy(obj, 'someFunction');
    

    这将替换 obj.someFunction 与间谍。如果您想回到原来的状态,请使用someSpy.restore()。

    您使用的是独立的间谍,所以没有什么可以恢复的。

    另外,因为您在beforeEach 中为每个测试创建新间谍,您不必在afterEach 中重置任何内容。这仅在您想重用间谍时才有用:

    describe('general visor methods tests', () => {
      let someSpy = sinon.spy(); // create the spy once
    
      afterEach(() => {
        someSpy.reset(); // reset after each test
      });
    
      ...
    });
    

    【讨论】:

    • 感谢您深入了解此细节/方面。每次编写测试时都会学到一些新东西,即使是在我认为自己有足够经验和很好理解的框架上。
    猜你喜欢
    • 2020-01-20
    • 2019-09-11
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    相关资源
    最近更新 更多