Skip to content

Commit

Permalink
fix: support userAgent option for jsdom environment (jestjs#11773)
Browse files Browse the repository at this point in the history
  • Loading branch information
nwalters512 authored and splincode committed Aug 24, 2021
1 parent abc1644 commit f3ac8d6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,7 @@
### Fixes

- `[jest-types]` Compat with `@types/node` v16 ([#11645](https://github.com/facebook/jest/pull/11645))
- `[jest-environment-jsdom]` Add support for `userAgent` option ([#11773](https://github.com/facebook/jest/pull/11773))
- `[jest-environment-node]` Add `Event` and `EventTarget` to node global environment. ([#11705](https://github.com/facebook/jest/issues/11705))
- `[jest-mock]` Fix `spyOn` to use `Object.prototype.hasOwnProperty` [#11721](https://github.com/facebook/jest/pull/11721)
- `[jest-resolver]` Add dependency on `jest-haste-map` [#11759](https://github.com/facebook/jest/pull/11759)
Expand Down
Expand Up @@ -27,4 +27,16 @@ describe('JSDomEnvironment', () => {

expect(env.fakeTimersModern).toBeDefined();
});

it('should respect userAgent option', () => {
const env = new JSDomEnvironment(
makeProjectConfig({
testEnvironmentOptions: {
userAgent: 'foo',
},
}),
);

expect(env.dom.window.navigator.userAgent).toEqual('foo');
});
});
8 changes: 7 additions & 1 deletion packages/jest-environment-jsdom/src/index.ts
Expand Up @@ -6,7 +6,7 @@
*/

import type {Context} from 'vm';
import {JSDOM, VirtualConsole} from 'jsdom';
import {JSDOM, ResourceLoader, VirtualConsole} from 'jsdom';
import type {EnvironmentContext, JestEnvironment} from '@jest/environment';
import {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
import type {Config, Global} from '@jest/types';
Expand All @@ -33,6 +33,12 @@ class JSDOMEnvironment implements JestEnvironment<number> {
constructor(config: Config.ProjectConfig, options?: EnvironmentContext) {
this.dom = new JSDOM('<!DOCTYPE html>', {
pretendToBeVisual: true,
resources:
typeof config.testEnvironmentOptions.userAgent === 'string'
? new ResourceLoader({
userAgent: config.testEnvironmentOptions.userAgent,
})
: undefined,
runScripts: 'dangerously',
url: config.testURL,
virtualConsole: new VirtualConsole().sendTo(options?.console || console),
Expand Down

0 comments on commit f3ac8d6

Please sign in to comment.