Jest: Cannot spyOn on a primitive value; undefined given

Created on 5 Oct 2019  路  3Comments  路  Source: facebook/jest

馃悰 Bug Report

I cant spy on any of my components

  const spyDidMount = jest.spyOn(Component.prototype, "componentDidMount");
  wrapper = shallow(<Component />, { disableLifecycleMethods: true });

Or

  wrapper = shallow(<Component />, { disableLifecycleMethods: true });
const spyDidMount = jest.spyOn(wrapper.instance(), "componentDidMount");

both are not working
wrapper.instance() show error => Cannot read property 'instance' of undefined
Component.prototype show error => Cannot spyOn on a primitive value; undefined given

To Reproduce

I have a sample provided to test

Expected behavior

I could spy on component

Link to repl or repo (highly encouraged)

https://codesandbox.io/s/kind-spence-sbuyb

```

Bug Report Needs Repro Needs Triage

All 3 comments

wrapper or wrapper.instance() is undefined for some reason (I don't use Enzyme) and that's why it fails. jest.spyOn seems to report correctly what's wrong. You need to fix your tests first.

I got this error when using jest.spyOn is this mean anything
Cannot spyOn on a primitive value; undefined given

I tried your repro and wrapper is undefined. Maybe at some point it's defined, but instance() returns undefined (because e.g. it's a non-class component without instance). And the message is pretty much descriptive. I don't see what else we can do. Fix your code first :)

Was this page helpful?
0 / 5 - 0 ratings