为什么开玩笑的模拟测试给我不确定?
我是学习玩笑模拟的新手。我正在尝试一个非常简单的测试。我有一个文件夹问候器。该文件夹具有文件“ preeter.js”和一个名为“ test ”的子文件夹。 ' test '文件夹的测试称为preeter.test.js。这是Code
engreter.js
function greet(fname, lname) {
return "hello " + greetWithName(fname, lname)
}
export function greetWithName(fname, lname) {
return fname + " : " + lname
}
export default greet
,测试是:
import greet, {greetWithName} from '../greeter'
jest.mock("../greeter")
describe('checks greeter module', () => {
it ('greet', () => {
greetWithName.mockReturnValue("hero");
expect(greet("a", "b")).toBe("hello hero") // fails
})
})
curios为什么期望(问候(“ a”,“ b”))。tobe(“ Hello Hero”)失败了,它是未定义的。不确定为什么?
当检查期望时( etchwithname (“ a”,“ b”))。tobe(“英雄”):通过!
I am new to learning jest mocks. I am trying out a very simple test. I have a folder greeter. This folder has a file 'greeter.js' and a subfolder called 'test'. The 'test' folder has a test called greeter.test.js. Here is the code
greeter.js
function greet(fname, lname) {
return "hello " + greetWithName(fname, lname)
}
export function greetWithName(fname, lname) {
return fname + " : " + lname
}
export default greet
and the test is:
import greet, {greetWithName} from '../greeter'
jest.mock("../greeter")
describe('checks greeter module', () => {
it ('greet', () => {
greetWithName.mockReturnValue("hero");
expect(greet("a", "b")).toBe("hello hero") // fails
})
})
Curios why expect(greet("a", "b")).toBe("hello hero") fails, it is undefined. Not sure why ?
When checked for expect(greetWithName("a", "b")).toBe("hero") : passes !!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
jest.mock('../ etcher')
正在模拟整个etcher.js
模块,并且由于您不提供oighturnvalue
对于问候
它返回undefined
。默认情况下,
jest.mock
模拟从模块中的所有导出,除非您提供模拟返回值,否则undefined
。您正在模拟ertenWithName
返回值,但engry
也被模拟。要获得所需的行为,您可以将
engry
移动到单独的模块(您不模拟),或使用jest.requireactual
在模块中嘲笑某些功能,而不是其他功能。jest.mock('../greeter')
is mocking the wholegreeter.js
module, and since you don't provide amockReturnValue
forgreet
it's returningundefined
.By default,
jest.mock
mocks all exports from a module to returnundefined
unless you provide mock return values. You're mockinggreetWithName
to return a value, butgreet
is also being mocked.To get the behavior you want, you could either move
greet
into a separate module (which you don't mock), or usejest.requireActual
to mock certain functions in a module but not others.