'How to mock global variable in Jest test?
In my Jest test case, I want to mock one global variable, but I am getting Cannot assign to '' because it is an import. . How to fix that?
I want to cover a scenario where I do have valid token then do something.
Tried this but no luck:
jest.mock('jwtToken', () => () => ({ jwtToken: 'abc' }));
Service.ts
export let token: string;
@Injectable()
export class MyService {
constructor(
) {
token = null;
}
/**
* Checks token expiration to avoid N calls to generate token.
* @returns token status
*/
public async myFunction() {
try {
if (token) {
// Do something
}
} catch (error) {
throw error;
}
}
}
Service.spec.ts
import { MyService, token } from './authz.service';
describe('MyService', () => {
let myService: MyService;
beforeEach(() => {
jest.resetAllMocks();
jest.resetModules();
myService = new MyService();
});
describe('myFunction()', () => {
it('My test case', async () => {
token = 123; // Cannot assign to 'jwtToken' because it is an import.
const output = await myService.myFunction();
expect(output).toEqual(true);
});
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
