Mock a TypeScript constant different in every Jest test
I'm struggling to mock a constant with Jest on a per test basis. I have it working with the code below, but the mock is "static" - I can't mock it differently for each test.
Code:
// allowList.ts
export const ALLOW_LIST = {
'1234': true
};
// listUtil.ts
import { ALLOW_LIST } from './allowList.ts';
export const checkList = (id: string) => {
if (ALLOW_LIST[id]) return true;
return false;
};
Test (working):
// listUtil.test.ts
import { checkList } from './listUtil';
jest.mock('./listUtil', () => {
return {
'5678': true
};
});
test('in list', () => {
expect(checkList('5678')).toBe(true);
});
test('not in list', () => {
expect(checkList('1234')).toBe(false);
});
What I would like (not working):
// listUtil.test.ts
import { checkList } from './listUtil';
test('in list', () => {
jest.mock('./listUtil', () => {
return {
'5678': true
};
});
expect(checkList('5678')).toBe(true);
});
test('not in list', () => {
jest.mock('./listUtil', () => {
return {
'9123': true
};
});
expect(checkList('1234')).toBe(false);
});
Is what I'm trying to do possible? This post is very similar and appears to work when mocking functions, but I'm having the same issue as the commenters of the accepted answer. I think I'm just not understanding how Jest performs mocking under the hood. I believe the working version works because the mock is hoisted and basically overwrites the real implementation, but I'm not sure how or if I can achieve that in each test.
I think one option would be to expose the ALLOW_LIST via a function:
// allowList.ts
const ALLOW_LIST = {
'1234': true
};
export const getAllowList = () => ALLOW_LIST;
and mock that, but am wondering if that's necessary.
1 answer
-
answered 2021-01-14 05:08
slideshowp2
You can use jest.doMock(moduleName, factory, options) to mock a module differently for each test.
E.g.
allowList.ts
:export const ALLOW_LIST = { '1234': true, };
listUtil.ts
:import { ALLOW_LIST } from './allowList'; console.log('ALLOW_LIST: ', ALLOW_LIST); export const checkList = (id: string) => { if (ALLOW_LIST[id]) return true; return false; };
listUtil.test.ts
:describe('65712158', () => { beforeEach(() => { jest.resetModules(); }); it('should in list', () => { jest.doMock('./allowList', () => ({ ALLOW_LIST: { 5678: true } })); const { checkList } = require('./listUtil'); expect(checkList('5678')).toBeTruthy(); }); it('should not in list', () => { jest.doMock('./allowList', () => ({ ALLOW_LIST: { 9123: true } })); const { checkList } = require('./listUtil'); expect(checkList('1234')).toBeFalsy(); }); });
unit test result:
PASS examples/65712158/listUtil.test.ts 65712158 ✓ should in list (2517 ms) ✓ should not in list (2 ms) console.log ALLOW_LIST: { '5678': true } at Object.<anonymous> (examples/65712158/listUtil.ts:2:9) console.log ALLOW_LIST: { '9123': true } at Object.<anonymous> (examples/65712158/listUtil.ts:2:9) -------------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s -------------|---------|----------|---------|---------|------------------- All files | 100 | 100 | 100 | 100 | listUtil.ts | 100 | 100 | 100 | 100 | -------------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 5.03 s
See also questions close to this topic
-
Use ngrx action props type across the app
I am using angular 11 and ngrx.
I have an action like this
export const createSelfChannelRequest = createAction( '[Self] Create Channel Request', props<{ channelType: ChannelType; storeName?: string }>() );
In another part of the app, I am using typed form to match a form to this action payload type :
new FormBuilder().group<{ channelType: ChannelType; storeName: string }>
I would like to, instead of doing this and WITHOUT having to create a separated interface, know if it was possible to do something like this
new FormBuilder().group<typeof createSelfChannelRequest> // to get only { channelType: ChannelType; storeName: string }
- Property 'icons' does not exist on type 'typeof React'. TS2339
-
next.js When I set strict to true, I got a type error
Development Environment
・react
・typescript
・next.jsstrict has been changed from false to true. An error of Type was displayed.
There is an error with the any type, but all Props are type-defined.Error Description
colorScheme: 'primary' | 'secondary' | 'brand'; 'colorScheme' is declared here.
error TS7053: Element implicitly has an 'any' type because expression of type '("twitter" | "facebook" | (string & {}) | "whiteAlpha" | "blackAlpha" | "gray" | "red" | "orange" | "yellow" | "green" | "teal" | "blue" | "cyan" | "purple" | "pink" | "linkedin" | "messenger" | "whatsapp" | "telegram" | undefined) & ("brand" | ... 2 more ... | "warning")' can't be used to index type 'Record<("twitter" | "facebook" | (string & {}) | "whiteAlpha" | "blackAlpha" | "gray" | "red" | "orange" | "yellow" | "green" | "teal" | "blue" | "cyan" | "purple" | "pink" | "linkedin" | "messenger" | "whatsapp" | "telegram" | undefined) & ("brand" | ... 2 more ... | "warning"), string>'. 31 colorScheme={colorScheme != 'brand' && COLORS[colorScheme]}
mport React from 'react'; import { Button as ChakraButton, ButtonProps } from '@chakra-ui/react'; import { FunctionComponent } from 'react'; export type AtomButtonProps = ButtonProps & { colorScheme: 'primary' | 'secondary' | 'brand'; size?: 'xs' | 'sm' | 'md' | 'lg'; }; const COLORS: Record<AtomButtonProps['colorScheme'], string> = { primary: 'blue', secondary: 'purple', brand: 'brand', }; ChakraButton.defaultProps = { colorScheme: 'primary', backgroundColor: '', size: 'md', }; export const Button: FunctionComponent<AtomButtonProps> = ({ colorScheme, size, children, ...props }) => { return ( <ChakraButton colorScheme={colorScheme != 'brand' && COLORS[colorScheme]} layerStyle={colorScheme === 'brand' && COLORS[colorScheme]} size={size} {...props} > {children} </ChakraButton> ); };
-
How to resolve async timeout in jest test case for async callback?
How to resolve async timeout in jest test case for function?
I worked with node js and jest test. I am facing issue while execute test case for one function "getToken()" that function sometimes getting late to provide response. So jest test case was failed and provide error related to below async timeout.
Error : Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
Please refer below for "getToken" function and test case for the same.
Actual Function: In refresh_keys.js file
exports.getToken = function(){ return new Promise(function(resolve, reject){ const tokenPayload = { 'client_id': CLIENTID, 'resource': RESOURCE, 'username': config.username, 'password': config.password, 'grant_type': 'password' }; const res = await fetch('https://idad.spadtoken.com/adfs/oauth2/token',{ method: 'POST', headers: { 'Accept': 'application/json' }, body: new URLSearchParams(tokenPayload) }); if(res.status != 200){ reject(res.message); } let tokenData = await res.json(); let access_token = tokenData.access_token; resolve(access_token); }); }
Test Case for Above function:In refresh_keys.test.js file
const refreshKeyTest = require("../refresh_keys"); it("Test case for function getToken", async()=>{ await refreshKeyTest.getToken().then(res => { expect(res).not.tobeNull(); }).catch(err => { }); }, 30000);
How can i resolve this issue related to timeout with test case for above getToken function? Please let me know your thoughts and guidance on how to pass and execute without failed the above test case for getToken function.
-
How to run Junit testclass inside jar- Struts- Intellij
I have a struts application with its dependencies bundled as jar. All the java files including testclasses are also bundled inside a jar(/ROOT/WEB-INF/lib). I am using Intellij to run JUNIT test. But when I configured edit configuration, It shows error
Junit not found in module modulename
how do I run my junit testcases. Is there any way that these testclasses called from jsp
-
pytests failing randomly in buildkite but not in local when using ThreadPoolExecutor
I have a function in python that does some validations on data it receives in parallel using
ThreadPoolExecutor
"""Sample code to test parallel""" from concurrent.futures import ThreadPoolExecutor, as_completed def fun(data): """Sample function to test parallel""" with ThreadPoolExecutor() as executor: executors_list = [] executors_list.append(executor.submit(validate_type, data)) executors_list.append(executor.submit(validate_range, data)) for executor_result in as_completed(executors_list): executor_result.result() def validate_type(data): """function to validate data type""" if not isinstance(data, list): raise Exception('invalid type') def validate_range(data): """function to validate range""" MIN_VALUE = 2 for el in data: if el < MIN_VALUE: raise Exception('value out of range')
I wrote unit tests to test this function
"""Test parallel""" from unittest import TestCase from .thread_parallel import fun class TestParallel(TestCase): """Test parallel class""" @patch(".thread_parallel.check_type") def test_fun_failure_with_wrong_type(self, check_type_mock): """Test failure with invalid type""" check_type_mock.return_value = False with self.assertRaises(Exception) as context: fun("invalid") self.assertEqual("invalid type", context.exception.args[0]) @patch(".thread_parallel.check_range") def test_fun_failure_with_invalid_range(self, check_range_mock): """Test failure with invalid range""" check_range_mock.return_value = False with self.assertRaises(Exception) as context: fun([1, 2, 3]) self.assertEqual("value out of range", context.exception.args[0])
These unit tests are passing without any issue in my local machine. But when I run these tests in buildkite, they are failing randomly. The following is one such case
self = <tests.unit.test_parallel.TestParallel testMethod=test_fun_failure_with_wrong_type> check_type_mock = <MagicMock name='check_type' id='140641443066600'> @patch(".thread_parallel.check_type") def test_fun_failure_with_wrong_type(self, check_type_mock): """Test failure with invalid type""" check_type_mock.return_value = False with self.assertRaises(Exception) as context: fun("invalid") > self.assertEqual("invalid type", context.exception.args[0]) E AssertionError: 'invalid type' != "'>=' not supported between instances of 'str' and 'int'" E - invalid type E + '>=' not supported between instances of 'str' and 'int' tests/unit/test_parallel.py:18: AssertionError
I think the mock we patched for one test is being used in another test for some reason. Why is this happening? How can I avoid this?
-
Adjacent sibling selector with Enzyme dose NOT work
I have html like below:
<input type ="text" id="textInput-FirstName" /> <div class="col error">warning Message</div>
I am trying to get the "warning Message", so I use the code below:
expect(wrapper.find('#textInput-FirstName + div').text()).toBe('warning Message');
But I got an error in the console saying "Method “text” is meant to be run on 1 node. 0 found instead."
I use the $('input#textInput-FirstName + div') in the console in chrome browser and it can find the node. I have no idea why it doesn't work with enzyme. Could anyone tell me is there something wrong? I use “expect(wrapper.find('.error').text()).toBe('warning Message')” and it works fine, but I need to use "input#textInput-FirstName + div" because I have another familiar nodes.
I use "react": "^16.9.0", "jest": "^24.9.0", "enzyme": "^3.11.0"
-
Ts and jest Best way to test routes
I'm starting with jest, and I'm trying to test a route, but I don't know what is the best way to do this, well the way I did it with docker, I go up the docker and start the server express but in my test i create it again and i'm getting my port already in use:
● Hello Word Route › should return a json with value: hello word listen EADDRINUSE: address already in use :::8080 50 | 51 | public start(): void { > 52 | this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => {
I have the following bootstrap to start my server:
class ApplicationServer implements Server { private express: Application; private logger: LoggerProvider; private server: http.Server constructor(logger: LoggerProvider) { this.express = express(); this.logger = logger; } public getExpress(): Application { return this.express } public getLogger():LoggerProvider { return this.logger; } public getServer():http.Server { return this.server; } public async close(): Promise<void> { try { this.logger.log(`info`, `closing the http server`, {}) this.server.close() this.logger.log(`info`, `Http server successfully closed`, {}) this.logger.log(`info`, `closing the database`, {}) await closeDB(); this.logger.log(`info`, `Database successfully closed`, {}) } catch (error) { this.logger.log(`error`, error.message, error) } } public async init(): Promise<void> { setupStaticFiles(this.express); setupMiddlewares(this.express); setupRoutest(this.express, this.logger); await connectDB(this.logger) } public start(): void { this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => { this.logger.log( `info`, `Server listening on port: ${process.env.APP_PORT || 8080}`, {} ); }); } } export default ApplicationServer;
factory:
export const SetupServer = (): Server => { const logger = new adptLogger({}) return new ApplicationServer(logger) }
start:
(async () => { const server = SetupServer(); try { await server .init() .then(() => server.start()) } catch (error) { console.error(error) server.getLogger().log(`error`, error.message, error) process.exit() } })();
and this is my test::
describe("Hello Word Route", () => { let server= {} as Server; beforeAll(async () => { server = SetupServer(); await server.init(); server.start(); }); afterAll(async () => { }); it("should return a json with value: hello word", async () => { await request(server.getExpress()) .post("api/hello-word") .send({hello: 'hello word'}) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); }); });
I would like to know what is the best practice to take in this situation to perform route tests my test fail:
Hello Word Route › should return a json with value: hello word listen EADDRINUSE: address already in use :::8080 50 | 51 | public start(): void { > 52 | this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => { | ^ 53 | this.logger.log( 54 | `info`, 55 | `Server listening on port: ${process.env.APP_PORT || 8080}`, at Function.listen (node_modules/express/lib/application.js:618:24) at ApplicationServer.start (src/application/infra/app.ts:52:32) at Object.<anonymous> (src/application/routes/hello-word-routes.test.ts:11:12) (node:113) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) (Use `node --trace-warnings ...` to show where the warning was created) (node:113) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:113) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
-
Mock a private method returns NPE or No method found
I'm trying to mimic the behaviour of a public class that includes private methods with PowerMockito.
Here is what those methods look like.
private ChannelSftp channelSftp = null; public List<RandomStuff> method throws Exception { if(condition1) { return methodToMock(); } } private List<RandomStuff> methodToMock() { String firstString = null; InputStream = null; try { firstString = getFirstString(); } catch (IOException e) { } } private String getFirstString() throws Exception { String firstString = null; Vector vs = channelSftp.ls(path); for (Object v : vs) { ... } return firstString; }
In the test, I tried using PowerMockito with those lines
PowerMockito.when(mock, "getFirstString").thenReturn(null); PowerMockito.when(mock, "methodToMock").thenReturn(null); assertNull(mock.method())
I get NullPointerException at
Vector vs = channelSftp.ls(path)
I added
PowerMockito.when(mock, "getChannelSftp").thenReturn(null);
as a 1st line, and I get No method found with 'channelSftp'
I think that I need to mock ls, and I don't know how. Any ressources? Ideas?
-
How to test HTTP attach() with a faker uploaded file in Laravel
I have a method on a controller that receive a file upload and then retransmits via HTTP Client to an external post API route. It works but I'm unable to test it properly: when I retrive to get the fake storage file (with Storage::get()) I obtain an empty string and so the attach() method on the HTTP call fails with this error: InvalidArgumentException: A 'contents' key is required
This is my controller's method:
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; use App\Http\Requests\StoreRequest; public function store(StoreRequest $request) { $data = [ 'name' => $request->name, // ... ]; $response = Http::withToken( $this->token ); if ($request->hasFile('file')) { $file = date('Ymd') . '-file.' . $request->file->extension(); $request->file->storeAs('files', $file); if (Storage::exists("files/$file")) { dump(Storage::get("files/$file")); // -> enter on if but empty string on test $response = $response->attach('file', Storage::get("files/$file"), $file); } } $response = $response->post($this->endpoint, $data); if ($response->successful()) { return redirect()->route('thankyou'); } }
and this is my test:
use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; /** @test */ public function check_that_store_works() { Storage::fake(); Http::fake(); $data = [ 'name' => $this->faker->firstName, 'cv' => UploadedFile::fake()->create('file.pdf'), ]; $file = date('Ymd') . '-file.pdf'; $this->post( route('files.store'), $data ) ->assertRedirect( route('thankyou') ); Storage::assertExists( "files/$file" ); }
-
Mocks are not returning values properly with mockitoextension.class (Junit5)
So i have this code, where im trying to mock that atendees receive the notifications:
@Mock Event event; @Mock Attendee attende; @InjectMocks EventNotificationServiceImpl eventNotificationService; @Test public void checkIfAttendesAreNotified() { event.addAttendee(attende); eventNotificationService.announce(event); System.out.println(attende.getNotifications()); List<Notification> notifications = attende.getNotifications(); for (Notification notification : notifications) { assertEquals("The next big event is coming!", notification.getMessage()); } }
however here i dont see that atendees receive any notifications.But when I put this code, i see attendes receive notifications:
@Mock Event event; @Mock Attendee attende; @InjectMocks EventNotificationServiceImpl eventNotificationService; @Test public void checkIfAttendesAreNotified() { attende = new Attendee(1L,"sara", "sara@example.com"); event = new Event(); event.addAttendee(attende); eventNotificationService.announce(event); System.out.println(attende.getNotifications()); List<Notification> notifications = attende.getNotifications(); for (Notification notification : notifications) { assertEquals("The next big event is coming!", notification.getMessage()); } }
Id like to know why mocks are not being inicitialized. Id like to not have to create the event and attendees objects in the tests since this bring me problems cause when i try to verify, attendees and events are not recognized as mocks. If someone can help me Id be very thankful! :)))
-
how to mock different values for same function jest?
I have a function where I take a time range as input and fetch 2 rows from my db. I need to get the difference of the field between the 1st and last data entry in the given range.
My function
async getUsage(start: Date, id: number) { const initial = await this.datarepo .createQueryBuilder('data') .where('data.deviceId = :id and data.RTC > :start') .setParameter('id', id) .setParameter('start', start) .orderBy('data.RTC', 'ASC') .getOne(); const final = await this.datarepo .createQueryBuilder('data') .where('data.deviceId = :id and data.RTC > :start') .setParameter('id', id) .setParameter('start', start) .orderBy('data.RTC', 'DESC') .getOne(); if (!final) return 0; const usage = final.reading- initial.reading; return usage; }
When I try to mock the function, I am getting the same data for each call even when I use mockResolvedValueOnce()
beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ DataService, { provide: getRepositoryToken(dataentity), useValue: { create: jest.fn(), save: jest.fn(), }, }, ], }).compile(); service = module.get<DataService>(DataService); datarepo= module.get(getRepositoryToken(dataentity)); }); it('gives the difference between energy readings for the given time range', async () => { datarepo.createQueryBuilder = jest.fn(() => ({ where: jest.fn().mockReturnThis(), setParameter: jest.fn().mockReturnThis(), orderBy: jest.fn().mockReturnThis(), getOne: jest .fn() .mockResolvedValueOnce(usageStart) .mockResolvedValueOnce(usageEnd), })); const result = await service.getUsage(new Date('2021-03-01T11:57:00.000Z'), 981); expect(result).toEqual(5); });
const usageStart = { reading: 70, RTC: '2021-03-01T11:57:45.000Z', }; const usageEnd = { reading: 75, RTC: '2021-03-01T12:57:45.000Z', };
I should get 5 as the result but I am getting 0
expect(received).toEqual(expected) // deep equality Expected: 5 Received: 0
-
How to make ts-jest work with import/export syntax of the js files that are being imported in my imports?
jest
fails to import the import of my import which is causingnpm run test
command to fail withSyntaxError: Unexpected token 'export'
at first line of mybar.ts
file. For this examplefoo.js
is a local file, not a node module. I can changefoo.js
tofoo.ts
and change the import inbar.ts
but that is not the solution.Files in my src folder:
foo.js
:
export const magicNumber = 42;
bar.ts
:
import { magicNumber } from './foo.js'; export const secondMagicNumber = magicNumber / 2;
bar.test.ts
:
import { secondMagicNumber } from './bar'; import assert from 'assert'; it('should work', function() { assert.strictEqual(secondMagicNumber, 21); });
Files in the root folder:
jest.config.js
:
export default { preset: 'ts-jest', testEnvironment: 'node', };
package.json
:
{ "name": "testing-with-jest", "version": "1.0.0", "description": "", "scripts": { "test": "jest" }, "author": "", "license": "ISC", "devDependencies": { "@types/jest": "^26.0.20", "jest": "^26.6.3", "ts-jest": "^26.5.2", "typescript": "^4.2.2" }, "type": "module" }
tsconfig.json
:
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "declaration": true, "moduleResolution": "node" }, "include": ["./src/**/*.ts"] }
-
Error in unit testing Svelte app within Nx Workspace project using Jest
I created an empty NxWorkspace, and then added a svelte project following the steps here. I added the component and its spec file using the command
nx g @nxext/svelte:c my-comp
. Until this point the tests run without any trouble, but after adding some TypeScript code to the MyComp.svelte file as below, the test stop working.<script lang="ts"> let temp: string; </script> <h1>Hello component!</h1> <h1> </h1>
The test file my-comp.spec.ts
import MyComp from './MyComp.svelte'; import { render } from '@testing-library/svelte'; it('it works', async () => { const { getByText } = render(MyComp); expect(getByText('Hello component!')); });
The error I receive is:
FAIL my-app apps/my-app/src/components/my-comp/my-comp.spec.ts ● Test suite failed to run ParseError: Unexpected token at error (../../node_modules/svelte/src/compiler/utils/error.ts:25:16) at Parser$1.error (../../node_modules/svelte/src/compiler/parse/index.ts:100:3) at Parser$1.acorn_error (../../node_modules/svelte/src/compiler/parse/index.ts:93:8) at Object.read_script [as read] (../../node_modules/svelte/src/compiler/parse/read/script.ts:51:10) at tag (../../node_modules/svelte/src/compiler/parse/state/tag.ts:205:27) at new Parser$1 (../../node_modules/svelte/src/compiler/parse/index.ts:52:12) at parse (../../node_modules/svelte/src/compiler/parse/index.ts:216:17) at Object.compile (../../node_modules/svelte/src/compiler/compile/index.ts:91:14) at Object.process (../../node_modules/svelte-jester/src/transformer.js:21:25) at ScriptTransformer.transformSource (../../node_modules/@jest/transform/build/ScriptTransformer.js:464:35)
the generated
jest.config.js
:module.exports = { displayName: 'my-app', preset: '../../jest.preset.js', globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.spec.json', }, }, transform: { '^.+\\.svelte$': 'svelte-jester', '^.+\\.[tj]s$': 'ts-jest', }, moduleFileExtensions: ['ts', 'js', 'html', 'svelte'], coverageDirectory: '../../coverage/apps/my-app', };
the
tsconfig.json
file:{ "extends": "../../tsconfig.base.json", "compilerOptions": { "moduleResolution": "node", "target": "es2017", /** Svelte Preprocess cannot figure out whether you have a value or a type, so tell TypeScript to enforce using `import type` instead of `import` for Types. */ "importsNotUsedAsValues": "error", "isolatedModules": true, /** To have warnings/errors of the Svelte compiler at the correct position, enable source maps by default. */ "sourceMap": true, /** Requests the runtime types from the svelte modules by default. Needed for TS files or else you get errors. */ "types": ["svelte"], "strict": false, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "files": [], "include": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.spec.json" } ] }
the
tsconfig.spec.json
:{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "../../dist/out-tsc", "module": "commonjs", "types": ["jest", "node", "@types/jest"] }, "include": [ "**/*.spec.ts", "**/*.spec.tsx", "**/*.spec.js", "**/*.spec.jsx", "**/*.d.ts" ] }
tsconfig.base.json
on the root of the NX workspace{ "compileOnSave": false, "compilerOptions": { "rootDir": ".", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "module": "esnext", "lib": ["es2017", "dom"], "skipLibCheck": true, "skipDefaultLibCheck": true, "baseUrl": ".", "paths": {} }, "exclude": ["node_modules", "tmp"] }
I am hopping, there's some easy fix in some of this files that I am not seeing.
Thanks in advance.