英文:
using sinon stub to test a method on an object
问题
我想在对象内部测试一个函数。 代码,我们将其称为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',但它并没有按预期工作。 我做错了什么?
英文:
I want to test a function inside an object. The code, lets call it someFile.js, is structured as below.
import someService from 'a-location';
const val = someService.getVal();
const AnObject = {
someMethod() {
if(val) //dosomething
}
}
export default AnObject;
In the test file, I have code as below
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();
})
})
I was hoping to receive 'my-val' when someService.getVal() is called in the someFile.js but it isn't working as expected. What am I doing wrong?
答案1
得分: 0
你应该在存根化后使用import()来动态导入someFile
中的AnObject
。
例如:
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
,这是一个存根化的值。
英文:
You should use import() to import the AnObject
from someFile
dynamically after stubbing.
E.g.
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();
});
});
Test result:
description
val: my-val
✓ more description
1 passing (8ms)
As you can see, the val
is my-val
which is a stubbed value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论