如何断言 jest 模拟的模块方法已被调用?

huangapple go评论62阅读模式
英文:

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 &#39;../../../../services/logs.service.js&#39;;

jest.mock(&#39;../../../../services/logs.service.js&#39;, () =&gt; ({
    log: jest.fn()
}));

expect(log).toHaveBeenCalledWith(2, &quot;foo&quot;); // JavaScript

TypeScript

import { log } from &#39;../../../../services/logs.service.js&#39;;

jest.mock(&#39;../../../../services/logs.service.js&#39;, () =&gt; ({
    log: jest.fn()
}));

const mockedLog = log as jest.MockedFunction&lt;typeof log&gt;;

expect(mockedLog).toHaveBeenCalledWith(2, &quot;foo&quot;);

huangapple
  • 本文由 发表于 2023年6月1日 18:25:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定