【问题标题】:How do I stub non object function using sinon如何使用 sinon 存根非对象函数
【发布时间】:2019-11-06 04:24:16
【问题描述】:

我有一个非对象函数

关于 getConfig.js

export default function () {
 /** do something **/
  return {
    appConfig: { status: true } 
    }
}

在我的主文件下

import getConfig from './getConfig';

export default function() {
 const { appConfig } = getConfig();
 
 if(appConfig.status) {
   console.log("do the right thing");
   else {
   console.log("do other things")
   }
  }
 }

如何使用 sinon 存根或模拟方法模拟 getConfig 函数?或者有没有更好的方法来设置 appConfig.status 属性为真或假?

我想执行以下操作,但它不起作用

import getConfig from './getConfig';
import main from './main';

test('should status to be true', () => {
  
  sinon.stub(getConfig).callsFake(sinon.fake.returns({status:true});
  expect(main()).toBe('to do the right thing')
}

【问题讨论】:

    标签: javascript unit-testing sinon


    【解决方案1】:

    getConfig 函数只返回一个对象,所以你应该只检查返回的值(对象)。你根本不需要 sinon。您需要做的是断言返回值。您可以使用mocha 测试运行程序来运行测试,并使用一个断言工具,如节点的内部assert 模块进行断言。

    “有没有更好的方法来设置 appConfig.status 属性为真或假?”给函数加个参数怎么样?

    // using default values for properties
    export default function(status = true) {
      // no need for additional `appConfig` property
      return { status };
    }
    

    测试(参见mocha 环境设置手册):

    import getConfig from './getConfig';
    import assert from 'assert';
    
    describe('getConfig', function() {
        it('should return { status: true } by default', function() {
          const ret = getConfig();
          assert.deepEqual(ret, { status: true });
        });
        it('should return { status: false } by passing `false`', function() {
          const ret = getConfig(false);
          assert.deepEqual(ret, { status: false });
        });
    });
    

    【讨论】:

    • 感谢您的回答我已经在顶部发布了我的函数框架,通常状态值在 getConfig 文件中计算,并根据某些逻辑返回状态真或假。有时 appConfig 不会有状态值
    • 不客气。这只是一个基本示例,您可以使用相同的逻辑来测试您的 main 函数,返回值而不是使用 console.log 函数并断言返回值。您还可以使用chai 断言库。
    【解决方案2】:

    好的,我找到了另一个仅使用 JEST 的替代解决方案

    jest.mock('./getConfig', () => (
     jest.fn()
     .mockReturnValueOnce({ appConfig: { status: true }})
     .mockReturnValueOnce({ appConfig: { status: false }})
    ))
    
    //The getConfig get replaced with the above mock function

    所以解决方案看起来像

    import main from './main';
    
    jest.mock('./getConfig', () => (
     jest.fn()
     .mockReturnValueOnce({ appConfig: { status: true }})
     .mockReturnValueOnce({ appConfig: { status: false }})
    ))
    
    
    test('should status to be true', () => {
      expect(main()).toBe('to do the right thing')
      expect(main()).toBe('to do the other things')
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-02
      • 2023-01-18
      • 2019-09-12
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 2021-02-20
      相关资源
      最近更新 更多