首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jest.fn().mockReturnValue("hello")在beforeAll()中调用时返回未定义的内容,但在beforeEach()中不返回

jest.fn().mockReturnValue("hello")在beforeAll()中调用时返回未定义的内容,但在beforeEach()中不返回
EN

Stack Overflow用户
提问于 2022-09-24 15:24:41
回答 1查看 91关注 0票数 1

为什么当我创建一个jest.fn()函数,然后在一个beforeAll()中调用它的mockReturnValue("hello")时,当我试图在测试中对它的值进行console.log时得到undefined,而在一个beforeEach()中调用mockReturnValue("hello")时却没有得到undefined

代码语言:javascript
运行
复制
import App from "./App"

describe("App", () => {

  const mock = jest.fn()

  beforeAll(() => {
    mock.mockReturnValue("hello")
  })

  beforeEach(() => {
  })

  afterEach(() => {
  })

  afterAll(() => {
  })

  it("should console.log the value 'hello'", () => {
    console.log(mock()) // undefined
  })
})

但是,当我在一个mockReturnValue("hello")中调用beforeEach时,它会打印hello

代码语言:javascript
运行
复制
import App from "./App"

describe("App", () => {

  const mock = jest.fn()

  beforeAll(() => {
  })

  beforeEach(() => {
   mock.mockReturnValue("hello")
  })

  afterEach(() => {
  })

  afterAll(() => {
  })

  it("should console.log the value 'hello'", () => {
    console.log(mock()) // hello
  })
})

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-25 23:42:01

多亏了@jonrsharpe,我才得以追踪我的问题。

我正在通过node_modules/react-scripts而不是node_modules/jest运行我的测试。

默认情况下,根据另一个StackOverflow question and answer

默认情况下,在set script node_modules/react-scripts/scripts/utils/createJestConfig.js中,jest配置是用"resetMocks": true设置的。

因此,我所做的,在我的package.json文件中放置了

代码语言:javascript
运行
复制
  "jest": {
    "resetMocks": false
  }

然后重新运行我的测试,它像预期的那样通过了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73838422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档