使用 sinon 存根测试对象上的方法

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

我想测试对象内部的函数。代码,我们称之为 someFile.js,结构如下。

import someService from 'a-location';

const val = someService.getVal();

const AnObject = {
  someMethod() {
   if(val) //dosomething
  }
}

export default AnObject;

在测试文件中,我有如下代码

import someService from 'a-location';
import AnObject from 'someFile';

describe("description", function(){
  it('more description', function() {
    sinon.stub(someService, 'getVal').returns('my-val');
    AnObject.someMethod();
})
})

我希望在 someFile.js 中调用 someService.getVal() 时收到“my-val”,但它没有按预期工作。我做错了什么?

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

你应该使用 import()

AnObject
动态地
 导入 
someFile 存根后.

例如

some-file.ts

import someService from './a-location';

const val = someService.getVal();

const AnObject = {
  someMethod() {
    console.log('val: ', val);
  },
};

export default AnObject;

a-location.ts

const someService = {
  getVal() {
    return 'real val';
  },
};

export default someService;

some-file.test.ts

import sinon from 'sinon';
import someService from './a-location';

describe('description', () => {
  it('more description', async () => {
    sinon.stub(someService, 'getVal').returns('my-val');
    const AnObject = (await import('./some-file')).default;
    AnObject.someMethod();
  });
});

测试结果:

  description
val:  my-val
    ✓ more description


  1 passing (8ms)

如您所见,

val
my-val
,这是一个存根值。

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