Javascript 模拟方法中的变量 [英] Javascript mock a variable inside a method
问题描述
我有这个对象:
import keys from './keys'
const obj = {
getData: async funcion(url) {
const key = await keys.getAccess()
return get(url, {
secret: key
}
})
}
}
我想用模拟值模拟 key
变量.我试过了:
I want to mock the key
variable with a mock value. I tried:
test('test', async() => {
const spyD = jest.spyOn(obj, 'getData');
expect(obj.getData).toHaveBeenCalledWith('/url', {secret: 'my mocked key') //but secret is undefined
})
...但我不能模拟 key
变量.如何从我的函数中模拟该变量?
... but i can't mock the key
variable. How to mock that variable from my function?
推荐答案
不能直接;范围已关闭,无法访问其中声明的变量.您可以传入创建 key
的函数,以便您可以模拟其实现,同时将原始函数作为默认值传递:
You can't directly; the scope is closed over, there is no way to gain access to a variable declared within it. You can pass in the function that creates key
instead so that you can mock its implementation, while passing the original function as a default:
const obj = {
getData: async function(url, getAccess = keys.getAccess) {
const key = await getAccess()
return get(url, {
secret: key
}
})
}
}
test('test', async () => {
const spyD = jest.spyOn(obj, 'getData');
const result = await obj.getData("/url", async () => "my mocked key");
expect(spyD).toHaveBeenCalledWith("/url");
})
这个测试现在应该通过了,result
将是 get
的返回值,用 "/url"
和 调用{秘密:我的模拟密钥"}
.
This test should now pass, and result
will be the return value of get
called with "/url"
and {secret: "my mocked key"}
.
或者,如果您不想修改obj
,您可以完全模拟getData
的实现以获得相同的结果:
Alternatively, if you would prefer not to modify obj
, you can mock the implementation of getData
altogether to get the same result:
test('test', async () => {
const spyD = jest.spyOn(obj, 'getData').mockImplementation(async (url) => {
return get(url, {secret: "my-mocked-key"})
});
const result = await obj.getData("/url");
expect(spyD).toHaveBeenCalledWith("/url");
})
这篇关于Javascript 模拟方法中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!