3

I am testing my React app and when it runs a test that executes the Web Cryptography API, specifically await crypto.subtle.generateKey I get the following error message

ReferenceError: crypto is not defined

It seems as if React Testing Library didn't have access to the library, which makes sense, since this is an API native to the browser, and React Testing Library simulates a library.

How can I add the library so that the test passes? Following the TDD principles, I shouldn't modify the code so that it passes the test.

subharb
  • 3,374
  • 8
  • 41
  • 72
  • 2
    You'll probably have to attach a dummy version to the window object in the `setupTests` file. Something like this: https://stackoverflow.com/questions/52612122/how-to-use-jest-to-test-functions-using-crypto-or-window-mscrypto – Jayce444 Aug 18 '20 at 08:38

2 Answers2

0

As @Jayce44 suggested you can just add a mock to the window object. It is a good pattern to erase any random component in your tests anyway (especially in TDD). Defining a fake/mock crypto module where you define the output of it based on the test case has many benefits to write solid test cases.Depending on the framework you are using this could look something like:

beforeEach(() => {
  setupCryptoWithExpectedValue(42)
});

test(() => {
  productionCodeUsingCrypto()
}
0

I met the same problem as you, but in fact he is not a problem。

because this API can only run in localhost and HTTPS environments.

therefore, the scenario where you make an error may be running in the HTTP environment

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 17 '22 at 18:23