Sinon在存根后调用原始方法

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

[尝试存根ES6导入方法。但是sinon调用了原始方法。

    //utils.js
    export function getUser(name) {
       return name + " has been fetched";
    }
    //user.js

    import { getUser } from './utils.js';

    export default function printName() {
      return getUser("user");
    }

    //user.test.js
    import sinon from 'sinon';

    import * as utils from '../src/utils.js';

    import printName from '../src/user.js';

    const assert = require('assert');

    describe('print name', () => {

      it('should fetch and print the user name', async () => {

        let utilsStub = sinon.stub(utils, 'getUser');

        utilsStub.withArgs("user").returns("test");

        assert.equal("test", printName());
      });

    });

在同一模块内调用方法时,它正确地存根,不确定是否有任何错误。帮助将不胜感激。

javascript ecmascript-6 import sinon stub
1个回答
0
投票

您的代码对我来说很好:

utils.ts

export function getUser(name) {
  return name + " has been fetched";
}

user.ts

import { getUser } from "./utils";

export default function printName() {
  return getUser("user");
}

user.test.ts

import sinon from "sinon";
import * as utils from "./utils";
import printName from "./user";

const assert = require("assert");

describe("print name", () => {
  it("should fetch and print the user name", async () => {
    let utilsStub = sinon.stub(utils, "getUser");
    utilsStub.withArgs("user").returns("test");
    assert.equal("test", printName());
  });
});

带有覆盖率报告的单元测试结果:

  print name
    ✓ should fetch and print the user name


  1 passing (10ms)

--------------|----------|----------|----------|----------|-------------------|
File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files     |    93.33 |      100 |       75 |    92.86 |                   |
 user.test.ts |      100 |      100 |      100 |      100 |                   |
 user.ts      |      100 |      100 |      100 |      100 |                   |
 utils.ts     |       50 |      100 |        0 |       50 |                 2 |
--------------|----------|----------|----------|----------|-------------------|

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

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