Imagine you have an application that imports a config object from another file, and then uses the config to control what it shows on the page.
1 | export default { |
1 | import Config from './Config' |
Can you change the Config
object from a Cypress end-to-end test?
🎁 You can find the source code in the repo bahmutov/stub-window-object-example
Set Config on the window
To let the test "know" the config values, the simplest is to assign it to a property of the window
object.
1 | import Config from './Config' |
The test can confirm the keys in the config object, and use the title from the config to check the page.
1 | it('sets the window config', () => { |
Tip: I am using // @ts-ignore
above some source lines to avoid fighting the TypeScript compiler.
Override the config object
If we can read the config object from the window object, we can also override it. We just need to define a custom property that lets us return a new value from the test. In the application, we make an intermediate variable to pass the config object.
1 | import _config from './Config' |
Our Cypress test can intercept the assignment "window.Config = Config" and replace its value and return its own object. We just need to make sure we are ready before the application loads its application code. We can do this in the onBeforeLoad
callback of the cy.visit command.
1 | it('overrides the config', () => { |
Combine the config object
We do not have to completely replace the application's config object. We can combine its value with some of our test properties.
1 | it('combines the config', () => { |
Mock Config module
We can go one step beyond the previous solutions. Instead of modifying the application code to expose the Config object, we can directly mock the src/Config.tsx
module in our JavaScript bundle (assuming the "standard" Webpack module format). We can do this using the plugin mock-in-bundle
1 | $ npm i -D mock-in-bundle |
From the spec file, specify the module and the new default export.
1 | import { mockInBundle } from 'mock-in-bundle' |
Boom 💣 the mock title is shown.
Happy testing!