I have a __mocks__
folder with a file called example.ts
in it
我有一个__mocks__文件夹,其中有一个名为Example.ts的文件
File Content (shortened for simplicity)
文件内容(为简单起见简称)
export let token: string | null = "exampleString";
I have a test file where I use this variable in all the test cases.
我有一个测试文件,其中我在所有测试用例中使用该变量。
There is one in particular where I want to override the value of this variable to be null
特别是在其中一个地方,我希望将此变量的值覆盖为空
Approaches tried:
尝试的方法:
- Use a proxy to try to intercept the variable when the function to be tested is called (no success, variable still set to
exampleString
- Use jest.spyOn to try and override the variable, still no success
- Used
jest.unmock('../../modules/__mocks__/example');
to try and use the real implementation of the file but no success
Has anyone got an idea on how to successfully override the value of the variable for a single test case?
有没有人知道如何成功覆盖单个测试用例的变量值?
Thanks
谢谢
更多回答
优秀答案推荐
You could shadow the typical mock by declaring a variable in the test's scope.
您可以通过在测试范围内声明一个变量来隐藏典型的模拟。
For example:
例如:
// __mocks__/example.ts
export const token = 'exampleString';
// __tests__/foo.spec.ts
import { token } from '../__mocks__/example.ts';
import a from '../foo.ts';
describe('foo', () => {
it('does something', () => {
const actual = foo.doSomething(token);
/* ... */
});
it('does something else', () => {
const token = null;
const actual = foo.doSomethingElse(token);
/* ... */
});
});
更多回答
Interesting concept of shadowing, wasn't aware of it, in my scenario though and my question may have induced this answer so apologies, the token variable is consumed directly from the function I am testing, i.e. I don't pass it as an argument. It gets imported to the file the function lives on
阴影的有趣概念,我没有意识到,在我的场景中,我的问题可能导致了这个答案,抱歉,令牌变量直接从我正在测试的函数中消费,即我不会将其作为参数传递。它被导入到函数所在的文件中
If the token isn't a parameter to the function your testing, when would it change? If it's constant throughout the life of your application, there's no need to test the case where it's null.
如果令牌不是您测试的函数的参数,它将在什么时候更改?如果它在应用程序的整个生命周期中都是常量,那么就没有必要测试它为空的情况。
token might be string | null
and I want to test both scenarios
标记可能是字符串|空,我想测试这两种情况
I'm not sure I understand. Could you please upload some sample code that references the token and some code that would cause it to change?
我不确定我是否明白。您能上传一些引用令牌的示例代码和一些会导致令牌更改的代码吗?
I get the token from a meta tag in the window. If it is there it is a string, if it isn't, it becomes null. There are only those two scenarios
我从窗口中的meta标签中获取令牌。如果它在那里,它是一个字符串,如果它不在,它就变成空的。只有这两种情况
我是一名优秀的程序员,十分优秀!