Sinon存根在导出的功能上不起作用

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

我试图对重新加载网页的函数进行存根。我正在使用摩卡,柴和锡农。

export function reloadPage() {
    window.location.reload();
}

这是我对函数进行存根的方式:

import * as ref from 'file/where/reloadpage/is/defined';

describe('...', function () {
    ...
    before(function () {
       this.reloadStub = sinon.stub(ref, 'reloadPage');
    });
});

它仍然没有正确地对方法进行存根。我的测试抛出“整页重新加载”错误。

我不知道我在做什么错。

javascript unit-testing mocha sinon chai
1个回答
0
投票

这是一个有效的示例:

index.ts

export function reloadPage() {
  console.log('reload');
  window.location.reload();
}

index.spec.ts

import * as ref from './';
import sinon from 'sinon';
import { expect } from 'chai';

describe('57519517', () => {
  let reloadStub;
  before(() => {
    reloadStub = sinon.stub(ref, 'reloadPage');
  });

  it('should mock reload page', () => {
    const logSpy = sinon.spy(console, 'log');
    ref.reloadPage();
    expect(reloadStub.calledOnce).to.be.true;
    expect(logSpy.notCalled).to.be.true;
  });
});

单元测试结果:

 57519517
    ✓ should mock reload page


  1 passing (12ms)

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57519517

© www.soinside.com 2019 - 2024. All rights reserved.