英文:
How can I assert that the jest mocked module method was called?
问题
我如何断言 jest 模拟的模块方法是否被调用了?
例如,在我的 .spec.js 文件中,我有以下 jest 模拟的模块:
jest.mock('../../../../services/logs.service.js', () => ({
log: jest.fn()
}));
现在,我想要断言 log 方法是否被调用。就像这样:
// log 被调用两次,传入文本 "foo"
expect(log).toHaveBeenCalledWith(2, "foo");
但是我无法访问 log
。我尝试将 log 的初始化移到 jest 模拟的模块外部,像这样:
const log = jest.fn();
jest.mock('../../../../services/logs.service.js', () => ({
log
}));
但我收到了以下错误:
jest.mock()
的模块工厂不允许引用任何超出作用域的变量。
英文:
How can I assert that the jest mocked module method was called?
E.g. in my .spec.js I have the following jest mocked module:
jest.mock('../../../../services/logs.service.js', () => ({
log: jest.fn()
}));
Now I would like to assert the log method. I.e. something like this:
//the log was called twice with the text "foo"
expect(log).toHaveBeenCalledWith(2, "foo");
But I can not access the log
. I tried putting the log initialization outside the jest mocked module, like so:
const log = jest.fn();
jest.mock('../../../../services/logs.service.js', () => ({
log
}));
But I got the error:
>The module factory of jest.mock()
is not allowed to reference any out-of-scope variables.
答案1
得分: 1
JavaScript
import { log } from '../../../../services/logs.service.js';
jest.mock('../../../../services/logs.service.js', () => ({
log: jest.fn()
}));
expect(log).toHaveBeenCalledWith(2, "foo"); // JavaScript
TypeScript
import { log } from '../../../../services/logs.service.js';
jest.mock('../../../../services/logs.service.js', () => ({
log: jest.fn()
}));
const mockedLog = log as jest.MockedFunction<typeof log>;
expect(mockedLog).toHaveBeenCalledWith(2, "foo");
英文:
You can do the following:
JavaScript
import { log } from '../../../../services/logs.service.js';
jest.mock('../../../../services/logs.service.js', () => ({
log: jest.fn()
}));
expect(log).toHaveBeenCalledWith(2, "foo"); // JavaScript
TypeScript
import { log } from '../../../../services/logs.service.js';
jest.mock('../../../../services/logs.service.js', () => ({
log: jest.fn()
}));
const mockedLog = log as jest.MockedFunction<typeof log>;
expect(mockedLog).toHaveBeenCalledWith(2, "foo");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论