【问题标题】:How do I test the returned value in Jest?如何在 Jest 中测试返回值?
【发布时间】:2020-12-29 08:20:17
【问题描述】:

我想用 Jest 测试一个简单的函数。我已多次阅读https://jestjs.io/docs/en/mock-functions,但我不确定出了什么问题,也无法在 stackoverflow 上找到明确的答案。我觉得这是一个非常简单的测试。

这是我的功能:

public hello(name: string) {
  return 'Hello ' + name
}

这是我的测试:

let hello = jest.fn()
jest.mock('./myfile.ts', () => {
  return hello
})

beforeEach(() => {
  hello('world')
})

describe('hello test', (){
  it('expects to return concatenated string', () => {
    expect(hello.mock.results[0].value).toBe('Hello world') // returns as undefined - Test fails
  })
})

对于 mock.results 而不是 'Hello world',我一直未定义。

我做错了什么?我觉得我忽略了一些非常简单的事情。

【问题讨论】:

    标签: javascript typescript unit-testing jestjs tdd


    【解决方案1】:

    您正在尝试模拟要测试的函数。您应该只模拟其他依赖项。

    这就足够了:

    expect(hello('world')).toBe('Hello world')
    

    【讨论】:

    • 看起来有效!我已经实现了一些导致问题的其他代码。谢谢你的回答!
    • 其实效率非常低。如果 Expect 返回 true 或 false 布尔值,则可以将其包装到自定义框架方法中,该方法将根据返回值执行其他操作(突出显示元素或红色文本)。
    猜你喜欢
    • 2018-03-24
    • 2018-01-27
    • 2023-01-30
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2023-01-24
    相关资源
    最近更新 更多