使用Sinon.JS的一个非常简单的间谍(在全局模块调用中……无法正常工作,怎么了?

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

我的测试对象是loader.ts

import * as dotenv from 'dotenv';

export class SimpleLoader {
  public load() {
    dotenv.config(); // I want to spy on this call
  }
}

因此,使用Sinon.JS(与Mocha&Chai一起,在loader.spec.ts中执行了以下操作:

import * as dotenv from 'dotenv';
import * as sinon from 'sinon';

describe('SimpleLoader', function() {
  // First spy on, then require SimpleLoader
  beforeEach(function() {
    this.dotenvSpy = sinon.spy(dotenv, 'config');
    this.SimpleLoader = require('./loader').SimpleLoader;
  });

  it('loads correctly using default options', function() {
    const loader = new this.SimpleLoader();
    loader.load(); // the call that should call the spy!

    console.log(this.dotenvSpy.getCalls()); // NOT WORKING - no calls, empty array []
  });

  afterEach(function() {
    this.dotenvSpy.restore();
  });
});

问题是,从未调用存根。

node.js typescript mocha chai sinon
1个回答
0
投票

这是一个可行的示例,只需将import * as dotenv from 'dotenv'更改为import dotenv from 'dotenv'

loader.ts

import dotenv from 'dotenv';

export class SimpleLoader {
  public load() {
    dotenv.config();
  }
}

loader.spec.ts

import dotenv from 'dotenv';
import sinon from 'sinon';
import { expect } from 'chai';

describe('SimpleLoader', function() {
  beforeEach(function() {
    this.dotenvSpy = sinon.spy(dotenv, 'config');
    this.SimpleLoader = require('./loader').SimpleLoader;
  });

  it('loads correctly using default options', function() {
    const loader = new this.SimpleLoader();
    loader.load();
    expect(this.dotenvSpy.calledOnce).to.be.true;
  });

  afterEach(function() {
    this.dotenvSpy.restore();
  });
});

单元测试结果覆盖率100%:

  SimpleLoader
    ✓ loads correctly using default options


  1 passing (152ms)

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |      100 |      100 |      100 |      100 |                   |
 loader.spec.ts |      100 |      100 |      100 |      100 |                   |
 loader.ts      |      100 |      100 |      100 |      100 |                   |
----------------|----------|----------|----------|----------|-------------------|

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

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