开玩笑的TypeError:this.props.fetchBitcoin不是一个函数

时间:2020-03-12 18:05:16

标签: javascript reactjs redux jestjs

我正在使用Jest运行测试,以在测试中运行,该测试应该检查是否使用Redux分派通过function PromptShortenPath { # https://stackoverflow.com/questions/1338453/custom-powershell-prompts function shorten-path([string] $path) { $loc = $path.Replace($HOME, '~') # remove prefix for UNC paths $loc = $loc -replace '^[^:]+::', '' # make path shorter like tabs in Vim, # handle paths starting with \\ and . correctly return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2') } function prompt { # our theme $cdelim = [ConsoleColor]::DarkCyan $chost = [ConsoleColor]::Green $cloc = [ConsoleColor]::Cyan write-host "$([char]0x0A7) " -n -f $cloc write-host ([net.dns]::GetHostName()) -n -f $chost write-host ' {' -n -f $cdelim write-host (shorten-path (pwd).Path) -n -f $cloc write-host '}' -n -f $cdelim return ' ' } if ($MyInvocation.InvocationName -eq "PromptShortenPath") { "`nWarning: Must dotsource '$($MyInvocation.MyCommand)' or it will not be applied to this session.`n`n . $($MyInvocation.MyCommand)`n" } else { . prompt } } 传递了一个函数。

这是测试:

props

但是当我跑步

describe("when mounted", () => { beforeEach(() => { props.fetchBitcoin = mockFetchBitcoin; loot = mount(<Loot {...props} />); }); it("fires the `fetchBitcoin()` from the props", () => { expect(mockFetchBitcoin).toHaveBeenCalled(); }); }); 我收到以下错误

this.props.fetchBitcoin();

接收道具的组件看起来像:

TypeError: this.props.fetchBitcoin is not a function

       9 |   }
      10 |   componentDidMount() {
    > 11 |     this.props.fetchBitcoin();
         |                ^
      12 |   }
      13 | }

fetchBitcoin()看起来像:

import React from "react";
import { Component } from "react";
import { connect } from "react-redux";
import { fetchBitcoin } from "../actions/bitcoin";

export class Loot extends Component {
  render() {
    return <h3>Bitcoin balance:</h3>;
  }
  componentDidMount() {
    this.props.fetchBitcoin();
  }
}

export default connect(state => state, { fetchBitcoin })(Loot);

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。

对我来说,解决方案是将if语句添加到React组件中,如下所示:

export class Loot extends Component {
  render() {
    return <h3>Bitcoin balance:</h3>;
  }
  componentDidMount() {
    if (this.props.fetchBitcoin) {

  }
}