I upgraded to Nestjs v8 yesterday and I suspect my issue is related to that.
Before, I was able to create a testing module like this:
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
...appModuleMetaData,
providers: [...appModuleMetaData.providers, TestingService],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
testingService = app.get('TestingService');
});
This does not seem to be possible anymore since Nest can't get the TestingService. Currently, I'm seeing the error:
Nest could not find TestingService element (this provider does not
exist in the current context)
I'd love to solve this somehow.
I think I figured it out by myself. Seems like string-based tokens were deprecated and I have to input the actual class:
testingService = app.get(TestingService); // <-- no string
Related
Introduction
Because there is no build in Auth library for nuxt 3 yet, I am trying to create my own composable called useAuth.
The Problem
I am getting a startPerformanceMeasurement error when i try to call the loginRedirect or loginPopup method.
Uncaught (in promise) TypeError: this.startPerformanceMeasurement is not a function
at PerformanceClient2.startMeasurement (PerformanceClient.ts:100:45)
at BrowserPerformanceClient2.startMeasurement (BrowserPerformanceClient.ts:46:55)
at RedirectClient2.<anonymous> (StandardInteractionClient.ts:204:64)
at step (_tslib.js:87:23)
at Object.next (_tslib.js:68:53)
at _tslib.js:61:71
at new Promise (<anonymous>)
at __awaiter (_tslib.js:57:12)
at StandardInteractionClient2.getDiscoveredAuthority (StandardInteractionClient.ts:202:115)
at RedirectClient2.<anonymous> (StandardInteractionClient.ts:142:48)
Code
composables/useAuth.js
import * as msal from '#azure/msal-browser'
let state = {
authService: null,
}
export const useAuth = () => {
// use public configuration from nuxt
var config = useAppConfig();
//create authentication instance
state.authService = new msal.PublicClientApplication(config.msalConfig);
//return signIn method
return {
signIn
}
}
const signIn = async () => {
const tokenRequest = {
scopes: [
'openid',
'offline_access',
'Users.Read'
],
}
const response = await state.authService
.loginRedirect(tokenRequest)
.then(() => {
})
.catch(err => {
console.log(err) //TypeError: this.startPerformanceMeasurement is not a function
});
}
Index.vue
<script setup>
if(process.client) {
const auth = useAuth()
auth.signIn()
}
</script>
Apparently this is a bug in the MSAL library.
As mentioned in this issue on Github, they're currently working on a fix.
As a temporary solution, you could downgrade to a previous version. Downgrading might be as simple as just removing the caret character (^) when referring to the version in your package.json.
Edit: They've released a fix as part of msal-common v9.1.1.
I tested by downgrading multiple releases and the first one working was #azure/msal-browser#2.31.0
Faced this issue too. It is caused due to a bug from Microsoft. The versions that work fine are:
"#azure/msal-browser": "2.32.0",
"#azure/msal-common": "9.0.1",
"#azure/msal-react": "1.5.0",
Please ensure to remove the ^ in the number to keep it pinned.
Watch https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/5569 for updates from MS.
I have the following setup:
// uuid-wrapper.ts
import { v4 as uuidV4 } from 'uuid';
const uuid: () => string = uuidV4;
export { uuid };
// uuid-wrapper.spec.ts
import { uuid } from './uuid-wrapper';
describe('uuid-wrapper', () => {
console.log(uuid());
});
This works fine runtime, but it breaks in test. I'm trying to migrate to Jest 29 and I'm getting the following error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
From uuid's repo I found a workaround which, after applied and my jest.config.js looks like this:
module.exports = {
moduleNameMapper: {
uuid: require.resolve("uuid"),
},
};
This gives me a different error but I still have no idea what it means:
> jest uuid-wrapper --no-coverage
FAIL src/uuid-wrapper/uuid-wrapper.spec.ts
● Test suite failed to run
TypeError: (0 , uuid_wrapper_1.uuid) is not a function
In fact, any function I export from this file (uuid-wrapper.ts) is not resolved. I have other tests that follow a similar pattern of reexporting packages but only this one breaks. I'm using uuid 9.0.0 and jest 29.1.2.
Edit: After a bit more testing, it turns out that anything I import into the test is "not a function".
uuid ships as an ESModule and Jest should not need to transform it. Add it to your transformIgnorePatterns in your Jest config:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(uuid))'],
}
Edit: After a bit more testing, it turns out that anything I import into the test is "not a function".
I had very similar symptoms once: builds and works as excepted, yet ...is not function in jest. The culprit was a circular dependency I accidentally introduced with my story. Maybe check for that.
As I suspected, the issue was in the naming. Renaming the files and directory to just wrapper solved the issue.
I would like to test a small React web app where I use the global fetch method.
I tried to mock fetch in this way:
global.fetch = jest.spyOn(global, 'fetch').mockImplementation(endpoint =>
Promise.resolve({
json: () => Promise.resolve(mockResponse)
})
);
... but the mock seems to be ignored, while the built-in fetch seems to be used: Error: connect ECONNREFUSED 127.0.0.1:80 ... looks like a failed call to the built-in fetch.
I then tried to use jest.fn instead of jest.spyOn:
global.fetch = jest.fn(endpoint =>
Promise.resolve({
json: () => Promise.resolve(mockResponse)
})
);
... and was surprised to see a different error. Now the mock seems to be taken into consideration, but at the same time is not working correctly:
TypeError: Cannot read property 'then' of undefined
8 | this.updateTypes = this.props.updateTypes;
9 | this.updateTimeline = this.props.updateTimeline;
> 10 | fetch('/timeline/tags')
| ^
11 | .then(res => res.json())
12 | .then(tags => tags.map(tag => <option value={tag} key={tag} />))
13 | .then(options => options.sort((a, b) => a.key.localeCompare(b.key)))
I find the documentation of Jest and React Testing Library a bit confusing, honestly. What might be the problem with what I am doing?
Edit
The React component I am trying to test is called "App", was generated with Create React App, and was changed to include a call to fetch. I can gladly provide the code for this component, but I believe that the problem lies in the tests.
At the beginning of my App.test.js file, I import React from 'react';, then import { render, fireEvent, waitFor, screen } from '#testing-library/react';, and finally import App from './App';. I subsequently attempt to mock fetch in one of the ways I described, and then declare the following test:
test('renders a list of items, upon request', async () => {
const app = render(<App />);
fireEvent.click(screen.getByText('Update'));
await waitFor(() => screen.getByRole('list'));
expect(screen.getByRole('list')).toBeInTheDocument();
expect(screen.getByRole('list')).toHaveClass('Timeline');
});
Finally, I end my test file with global.fetch.mockRestore();.
That there's ECONNREFUSED error instead of fetch is not defined means that fetch has been polyfilled. It's not a part of JSDOM and isn't polyfilled by Jest itself but is specific to current setup. In this case the polyfill is provided by create-react-app.
It's always preferable to mock existing global function with jest.spyOn and not by assigning them as global properties, this allows Jest to do a cleanup. A thing like global.fetch = jest.spyOn(global, 'fetch') should never be done because this prevents fetch from being restored. This can explain TypeError: Cannot read property 'then' of undefined error for seemingly correctly mocked function.
A correct and safe way to mock globals is to mock them before each test and restore after each test:
beforeEach(() => {
jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest.fn().mockResolvedValue(mockResponse)
})
});
afterEach(() => {
jest.restoreAllMocks();
});
There should be no other modifications to global.fetch in order for a mock to work correctly.
A preferable way to restore mocks and spies is to use configuration option instead of jest.restoreAllMocks because not doing this may result in accidental test cross-contamination which is never desirable.
Another reason for TypeError: Cannot read property 'then' of undefined error to appear is that Jest incorrectly points at fetch line, and the error actually refers to another line. This can happen if source maps don't work correctly. If fetch is mocked correctly and there are other then in the same component, it's a plausible explanation for the error.
What is the equivalent of the below code in Jest.
let mockHeroService = jasmine.createSpyObj(['getHeros', 'addHero', 'deleteHero']);
I would like to use it the testBed.
TestBed.configureTestingModule({
providers: [
{
provide: HeroService,
useValue: mockHeroService
}
]
});
My understanding is that, with jest, you can only spy on one method of a service like
const spy = jest.spyOn(HeroService, 'getHeros');
Thanks for helping
There's no equivalent because it doesn't have much uses. Jest is focused on modular JavaScript and generates auto-mocks (stubs) with jest.mock and jest.createMockFromModule.
The problem with auto-mocks is that they result in unspecified set of functions that behave differently from original ones and can make the code that uses them to work incorrectly or silently fail.
A mock with no implementation can be defined as:
let mockHeroService = { getHeros: jest.fn(), ... };
Most times some implementation is expected:
let mockHeroService = { getHeros: jest.fn().mockReturnValue(...), ... };
I'm using react-testing-library to test a simple component which has a nested react-router-dom's <Link> inside of it and I am getting this error:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I solved it by mocking the Link:
jest.mock('react-router-dom', () => ({
Link: jest.fn().mockImplementation(({ children }) => {
return children;
}),
}));
That way I can test my component normally:
test('render MyComponent with <Link>', async () => {
const myListOfLinks = mockLinks();
render(<MyComponent parents={myListOfLinks} />);
const links = await screen.findByTestId('my-links');
expect(MyComponent).toBeInTheDocument();
});
I had similar issue with Link component being undefined. In our case it was caused by existing jest mock. There was a file in our codebase under __mocks__/react-router-dom.js which didn't provide an implementation for Link. So all other tests were using mocked implmentation of react-router-dom module. Jest uses convention for automatic mocking of modules. Removing this mock solved the issue