簡體   English   中英

如何使用 sinon 存根非 object function

[英]How do I stub non object function using sinon

我有一個非 object function

在 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 function? 或者有沒有更好的方法來設置 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') }

getConfig function 只返回 object 所以你應該檢查返回的值(object。)你根本不需要 sinon。 您需要做的是斷言返回值。 您可以使用mocha測試運行器來運行測試,並使用斷言工具(如節點的內部assert模塊)進行斷言。

“有沒有更好的方法來設置 appConfig.status 屬性為真或假?” 給 function 添加一個參數怎么樣?

// 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 });
    });
});

好的,我找到了另一個僅使用 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') }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM