我想测试对象内部的函数。代码,我们称之为 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”,但它没有按预期工作。我做错了什么?
你应该使用 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
,这是一个存根值。