Reputation: 3472
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.
Upvotes: 3
Views: 8976
Reputation: 1
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
Upvotes: 0
Reputation: 53
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()
}
Upvotes: 0