Amit
Amit

Reputation: 51

TypeError: Cannot stub non-existent own property fetch - Sinon, Pact

TypeError: Cannot stub non-existent own property fetch

declare namespace NodeJS {
  interface Global {
    fetch: (url: string, options ? : Object) => Promise < any > ;
  }
}
declare let global: NodeJS.Global;

it("should handle fetch throwing an error message", () => {
  const fetchFailure = "Test fetch error!";
  const fetchStub: sinon.SinonStub =
    sinon.stub(global, "fetch").callsFake(
      (url: string, options ? : Object): Promise < any > => {
        return new Promise((resolve, reject) => {
          throw (fetchFailure);
        });
      });
  try {
    return getConfigTest.getData(arguments)
      .then(() => {
        expect.fail(null, null, "Attempt to retrieve when no configuration exists should have thrown exception");
      })
      .catch((reason) => {
        if (reason instanceof someError) {
          expect(reason).to.equals("throwing error");
        } else {
          expect(reason).instanceOf(Error);
          expect(reason.message).to.equals("The request failed.");
        }
      });
  } finally {
    fetchStub.restore();
  }
});

Note: I am calling getData method and getData returning another method handle-fetch and inside handle fetch 'fetch' is getting used which I am stubbing here.

I am using this method in the Pact integration test. I am stubbing the fetch method and returning my own data without interacting with the actual method.

Can anybody help me with this. If you need any extra info. Please let me know in the comment section ?

Update:-

export async function getData(arguments): Promise < dataConfig > {
    const json: any = await handle - fetch(`path_to_Api);
  return json as dataConfig;
}


export async function handle-fetch<T>(arguments): Promise<T> {
  let response: any;
  let apiErr: any;

  options = _.merge({
    headers: {
      "Accept": "application/json"
    }
  }, options);

  try {
    response = await fetch(url, options); // **here is the method which i want to stub**

I have written a few tests for the correct id. But I was writing a test in case of failure to fetch the handle-fetch method.

In my other node project, I have done this way and it is working perfectly. But this is a react project. Do I need to install anything specific which I am not getting by default?

Upvotes: 1

Views: 3548

Answers (1)

Matthew Fellows
Matthew Fellows

Reputation: 4065

  1. Assuming you are trying to somehow mock the standard global, I don't think you can do it this way. Having attempted to run that code myself, fetch is indeed not applied to the global object.
  2. I'm not sure what relevance this has to a Pact test? Mocking the fetch object would certainly not be something you'd want to be doing as part of a Pact test.

What are you trying to achieve?

Another option would be to create a new collaborating service object that performs the fetch, and mock that out instead.

Upvotes: 1

Related Questions