javascript - 模拟来自同一个类的 promise 返回方法

标签 javascript unit-testing jestjs

我想模拟/ stub 一个类方法的解析,该类方法在测试同一类的另一个方法时返回一个 promise 。我正在使用jest

我有以下类 Blah,我想测试其中的 foo() 方法:

export default class Blah {
  foo () {
    this.bar().then(result => {
      // some logic here
    })
  }

  bar () {
    return new Promise(function (resolve, reject) {
      // fetches some stuff over the network
      resolve('hello world')
    })
  }
}

因为 foo() 使用 bar() - 一个通过网络执行操作的 promise 返回方法 - 我想模拟 bar( );;假设让它解决发生了什么

假设测试如下所示:

import Blah from './blah'

test('foo() - bar() resolves "what up"', () => {
  const blah = new Blah()
  // mock blah.bar() so that is resolves "what up"

  // {some assertions on blah.foo() here}
})

这是我第一次使用 jest,并且我已经通读了文档,但我仍然很难理解这个案例。

如何在测试 foo() 时模拟 bar() 的解析值?

最佳答案

仍然只是 JavaScript 意味着任何对象属性都可以动态覆盖:

// in the test file
const blah = new Blah();
blah.bar = _ => Promise.resolve("what up");

// now some assertions about blah.foo

关于javascript - 模拟来自同一个类的 promise 返回方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610380/

相关文章:

javascript - IIS 应用程序 + JavaScript

Javascript 环境变量

javascript - 在 Javascript/underscore 上按对象键降序排序

unit-testing - 为以下 meteor 代码写一个mocha单元测试代码

node.js - 如何在 Mocha 测试中模拟无连接

javascript - 如何在 JS 中设置从函数返回的两个全局对象?

reactjs - 如何使用react-testing-library在容器内的元素上fireEvent.scroll?

javascript - 每次从函数中得到相同的结果

node.js - 当客户端发出时如何测试 socket.io 服务器

javascript - Node 模块没有被正确解析以进行测试?