admin管理员组

文章数量:1134246

Say I have a class I wish to test, this class calls jsonFetch to fetch data. However to make it useful the class has a catch-all for exceptions. The library that is handling these "stores" has a custom "env" variable that can be set at creation to provide my own overloaded jsonfetch function.

To do this I was also writing a custom mock client for Jest, that mocks these functions, where you could register a list of URLs and then if the URL isn't there it should trigger/give feedback that a test fails.

export class MockClient {
  getFetcher(method: string, url: string) {
    return undefined
  }

  jsonFetch = async (url: string, options?: URLParameters) => {
    const method = options?.method?.toLowerCase() || "get";
    const fetcher = this.getFetcher(method, url);
    expect(fetcher).not.toBeUndefined(); 
    // here I wish to trigger something if the fetcher is "undefined".
    // here I wish to trigger something if the fetcher is "undefined".
    await fetcher?.jsonFetch(url, options);
  };
}

And it would be used (considering we test MyClass):

class MyClass {
  env: any;
  constructor(env: any) {
    this.env = env;
  }
  async load() {
    try {
      await this.env?.jsonFetch("badurl");
    } catch (error) {
      console.log(error);
    }
  }
}

describe("testing quick access store", () => {
  const client: MockClient2 = new MockClient2();
  let env: Record<string, any>;

  beforeAll(() => {
    // client.registerRoute({"response": "hello world"}, "/proper-url/");
    env = {
      jsonFetch: client.jsonFetch,
    }
  });

  test("Load data from", async () => {
    const store = QuickAccessStore.create({}, env);
    //TODO: FUTURE TEST HEREx
    const testObject = new MyClass(env);
    testObject.load();
  });
});

However I notice that no error is shown, the test seems to succeed. If I raise an error the same thing happens.

So how to guarantee that test will fail from the mock? Independent of how the MyClass is implemented? And in a way I could reuse the MockClient class easily?

本文标签: javascriptHow to make a custom 39trigger39 for JestStack Overflow