为什么当我创建一个jest.fn()
函数,然后在一个beforeAll()
中调用它的mockReturnValue("hello")
时,当我试图在测试中对它的值进行console.log时得到undefined
,而在一个beforeEach()
中调用mockReturnValue("hello")
时却没有得到undefined
。
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
。
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
})
})
发布于 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
文件中放置了
"jest": {
"resetMocks": false
}
然后重新运行我的测试,它像预期的那样通过了
https://stackoverflow.com/questions/73838422
复制相似问题