Null error when using .createInvite method in v13 API - discord

I am using this basic code to have a bot generate an invite link to a server - where guild ID is the string of my guild ID:
const Guild = await client.guilds.fetch(guildId);
const invite = await Guild.systemChannel.createInvite({
maxAge: 14,
maxUses: 10,
unique: true
});
Upon doing this, I receive the error:
TypeError: Cannot read properties of null (reading 'createInvite')
I wonder if anyone could possibly point out if I used this method incorrectly?
Just for some extra information, my guild object is returned fine as below:
<ref *2> Guild {
id: 'XXXXXXXXXX',
name: 'NAMEHERE',
icon: 'a_479390a16bfef56aee3c39330d4d2e3e',
features: [
'MEMBER_PROFILES',
'ROLE_ICONS',
'PRIVATE_THREADS',
'THREE_DAY_THREAD_ARCHIVE',
'SEVEN_DAY_THREAD_ARCHIVE',
'INVITE_SPLASH',
'BANNER',
'ANIMATED_ICON'
],
commands: <ref *1> GuildApplicationCommandManager {
permissions: ApplicationCommandPermissionsManager {
manager: [Circular *1],
guild: [Circular *2],
guildId: 'CENSORED',
commandId: null
},
guild: [Circular *2]
},
members: GuildMemberManager { guild: [Circular *2] },
channels: GuildChannelManager { guild: [Circular *2] },
bans: GuildBanManager { guild: [Circular *2] },
roles: RoleManager { guild: [Circular *2] },
presences: PresenceManager {},
voiceStates: VoiceStateManager { guild: [Circular *2] },
stageInstances: StageInstanceManager { guild: [Circular *2] },
invites: GuildInviteManager { guild: [Circular *2] },
deleted: false,
available: true,
shardId: 0,
splash: '53c57d1053959d572635640ef34aecce',
banner: null,
description: null,
verificationLevel: 'MEDIUM',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 459,
large: true,
applicationId: null,
afkTimeout: 300,
afkChannelId: null,
systemChannelId: null,
premiumTier: 'TIER_2',
premiumSubscriptionCount: 9,
explicitContentFilter: 'DISABLED',
mfaLevel: 'NONE',
joinedTimestamp: 1634610823632,
defaultMessageNotifications: 'ONLY_MENTIONS',
systemChannelFlags: SystemChannelFlags { bitfield: 0 },
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: null,
publicUpdatesChannelId: null,
preferredLocale: 'en-US',
ownerId: 'CENSORED',
emojis: GuildEmojiManager { guild: [Circular *2] },
stickers: GuildStickerManager { guild: [Circular *2] }
}

As per the discord.js docs for Guild#systemChannel, that property can be null, which means not every Guild has a systemChannel. You might want to check if it is null before the creating the invite, so you can choose another channel in case it is.

Related

Discord.js message collector

I am trying to wait for a response after the initial spec command is given. The two options would be See or Change and would reply with the messages given.
if (command == 'spec'){
message.channel.send("See or Change?");
const collector = new Discord.MessageCollector(message.channel, m => m.author.id == message.author.id, { time: 10000 });
console.log(collector)
collector.on('collect', m => {
if (message.content == "See") {
message.channel.send("You Want To See Someones Spec OK!");
} else if (message.content == "Change") {
message.channel.send("You Want To Change Your Spec OK!");
}
})
}
An error occurs instead giving me this large amount of code. THe bot starts up but after the command is given it crashes. Would love if someone helped me out since i've been stuck on this for a while.
MessageCollector {
_events: [Object: null prototype] {
end: [Function: bound onceWrapper] { listener: [Function (anonymous)] }
},
_eventsCount: 1,
_maxListeners: undefined,
filter: [Function (anonymous)],
options: [Function (anonymous)],
collected: Collection(0) [Map] {},
ended: false,
_timeout: null,
_idletimeout: null,
handleCollect: [Function: bound handleCollect] AsyncFunction,
handleDispose: [Function: bound handleDispose] AsyncFunction,
channel: <ref *1> TextChannel {
type: 'GUILD_TEXT',
guild: Guild {
id: '886817539194249227',
name: 'CULT OF PINIS',
icon: '67aad2f5b83706c317be25b3d322774e',
features: [Array],
commands: [GuildApplicationCommandManager],
members: [GuildMemberManager],
channels: [GuildChannelManager],
bans: [GuildBanManager],
roles: [RoleManager],
presences: PresenceManager {},
voiceStates: [VoiceStateManager],
stageInstances: [StageInstanceManager],
invites: [GuildInviteManager],
scheduledEvents: [GuildScheduledEventManager],
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 'NONE',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 21,
large: false,
premiumProgressBarEnabled: false,
applicationId: null,
afkTimeout: 300,
afkChannelId: null,
systemChannelId: '886972109383958588',
premiumTier: 'TIER_1',
premiumSubscriptionCount: 2,
explicitContentFilter: 'DISABLED',
mfaLevel: 'NONE',
joinedTimestamp: 1640578542092,
defaultMessageNotifications: 'ALL_MESSAGES',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: null,
publicUpdatesChannelId: null,
preferredLocale: 'en-US',
ownerId: '528290518472458240',
emojis: [GuildEmojiManager],
stickers: [GuildStickerManager]
},
guildId: '886817539194249227',
parentId: '888833493168173076',
permissionOverwrites: PermissionOverwriteManager { channel: [Circular *1] },
messages: MessageManager { channel: [Circular *1] },
threads: ThreadManager { channel: [Circular *1] },
nsfw: false,
id: '887163660353552484',
name: '🤖-pinis-bot-commands-🤖',
rawPosition: 10,
topic: null,
lastMessageId: '925637522988597298',
rateLimitPerUser: 0
},
received: 0,
_handleChannelDeletion: [Function: bound _handleChannelDeletion],
_handleThreadDeletion: [Function: bound _handleThreadDeletion],
_handleGuildDeletion: [Function: bound _handleGuildDeletion],
[Symbol(kCapture)]: false
}
Where you handle the collector event (on collect) you define the message object to be called "m" and then you check "message"'s content. There is the mistake.
collector.on('collect', m => {
if (m.content == "See") {
message.channel.send("You Want To See Someones Spec OK!");
} else if (m.content == "Change") {
message.channel.send("You Want To Change Your Spec OK!");
}
})
But this doesn't look like a reason the bot to crash. If it still crashes it must be from something else.

Discord.js V13 msg.author.id returning undefined

I have this message, and it has multiple values inside of it, and I'm trying to access the author.id part. I thought I was supposed to do something like msg.author.id, but that just returns undefined.
[
'918149237416558622',
<ref *1> Message {
channelId: '918144635782701097',
guildId: '906210773989203990',
deleted: false,
id: '918149237416558622',
createdTimestamp: 1638974236588,
type: 'DEFAULT',
system: false,
content: 'jamaal',
author: User {
id: '346315018696130563',
bot: false,
system: false,
flags: [UserFlags],
username: 'yAy',
discriminator: '4998',
avatar: 'ddaae73d9a3c8ebf564f2dd1c664bcb4',
banner: undefined,
accentColor: undefined
},
pinned: false,
tts: false,
nonce: null,
embeds: [],
components: [],
attachments: Collection(0) [Map] {},
stickers: Collection(0) [Map] {},
editedTimestamp: null,
reactions: ReactionManager { message: [Circular *1] },
mentions: MessageMentions {
everyone: false,
users: Collection(0) [Map] {},
roles: Collection(0) [Map] {},
_members: null,
_channels: null,
crosspostedChannels: Collection(0) [Map] {},
repliedUser: null
},
webhookId: null,
groupActivityApplication: null,
applicationId: null,
activity: null,
flags: MessageFlags { bitfield: 0 },
reference: null,
interaction: null
]
Do I have to add some extra parts or something? I tried doing things like msg[0].author.id, but it still returns undefined either way. Can anyone help me out here?
Nevermind, I found the answer. I was supposed to do msg[1].author.id instead of msg.author.id

Discord.js v13 Invite tracker

Finally getting around to updating my bot from v12 to v13 and having an issue that I can't seem to solve. I have an invite tracker that works perfectly on v12 but will not function on v13. I have included the code below, the commented lines are the v12 code that I know needed changing for v13.
// const Discord = require('discord.js')
const {
Client,
Intents
} = require('discord.js')
// const client = new Discord.Client({
// partials: ['MESSAGE', 'CHANNEL', 'REACTION']
// })
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, Intents.FLAGS.GUILD_INTEGRATIONS, Intents.FLAGS.GUILD_WEBHOOKS, Intents.FLAGS.GUILD_INVITES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MESSAGE_TYPING, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.DIRECT_MESSAGE_REACTIONS, Intents.FLAGS.DIRECT_MESSAGE_TYPING],
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
})
const guildInvites = new Map()
// client.on('inviteCreate', async invite => guildInvites.set(invite.guild.id, await invite.guild.fetchInvites()))
client.on('inviteCreate', async invite => guildInvites.set(invite.guild.id, await invite.guild.invites.fetch()))
client.once('ready', () => {
client.guilds.cache.forEach(guild => {
//guild.fetchInvites()
guild.invites.fetch()
.then(invites => guildInvites.set(guild.id, invites))
.catch(err => {
console.log(err)
console.log(guildInvites)
client.channels.cache.get('channelId').send({
content: `${err}`
})
})
})
})
client.on('guildMemberAdd', async member => {
const cachedInvites = guildInvites.get(member.guild.id)
// const newInvites = await member.guild.fetchInvites()
const newInvites = await member.guild.invites.fetch()
guildInvites.set(member.guild.id, newInvites)
try {
const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code).uses < inv.uses)
console.log(cachedInvites)
console.log(newInvites)
console.log(usedInvite)
console.log(`The code ${usedInvite.code} was just used by ${member.user.username}.`)
} catch (err) {
console.log(err)
client.channels.cache.get('channelId').send({
content: `${err}`
})
}
})
This is the console log result:
console.log(cachedInvites) => returns below
Collection(2) [Map] {
'11111111' => Invite {
guild: Guild {
id: 'xxxx',
name: "Testing Server",
icon: null,
features: [Array],
commands: [GuildApplicationCommandManager],
members: [GuildMemberManager],
channels: [GuildChannelManager],
bans: [GuildBanManager],
roles: [RoleManager],
presences: PresenceManager {},
voiceStates: [VoiceStateManager],
stageInstances: [StageInstanceManager],
invites: [GuildInviteManager],
deleted: false,
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 'LOW',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 3,
large: false,
applicationId: null,
afkTimeout: 900,
afkChannelId: 'xxxx',
systemChannelId: 'xxxx',
premiumTier: 'NONE',
premiumSubscriptionCount: 0,
explicitContentFilter: 'ALL_MEMBERS',
mfaLevel: 'NONE',
joinedTimestamp: 1633812225872,
defaultMessageNotifications: 'ONLY_MENTIONS',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: 'xxxx',
publicUpdatesChannelId: 'xxxx',
preferredLocale: 'en-US',
ownerId: 'xxxx',
emojis: [GuildEmojiManager],
stickers: [GuildStickerManager]
},
code: '11111111',
presenceCount: null,
memberCount: null,
temporary: false,
maxAge: 604800,
uses: 40,
maxUses: 0,
inviter: User {
id: 'xxxx',
bot: false,
system: false,
flags: [UserFlags],
username: 'xxxx',
discriminator: 'xxxx',
avatar: 'xxxx',
banner: undefined,
accentColor: undefined
},
targetUser: null,
targetApplication: null,
targetType: null,
channel: TextChannel {
type: 'GUILD_TEXT',
deleted: false,
guild: [Guild],
guildId: 'xxxx',
parentId: 'xxxx',
permissionOverwrites: [PermissionOverwriteManager],
messages: [MessageManager],
threads: [ThreadManager],
nsfw: false,
id: 'xxxx',
name: 'welcome',
rawPosition: 3,
topic: null,
lastMessageId: 'xxxx',
rateLimitPerUser: 0
},
createdTimestamp: 1633922331801,
_expiresTimestamp: null,
stageInstance: null
},
'22222222' => Invite {
guild: Guild {
id: 'xxxx',
name: "Testing Server",
icon: null,
features: [Array],
commands: [GuildApplicationCommandManager],
members: [GuildMemberManager],
channels: [GuildChannelManager],
bans: [GuildBanManager],
roles: [RoleManager],
presences: PresenceManager {},
voiceStates: [VoiceStateManager],
stageInstances: [StageInstanceManager],
invites: [GuildInviteManager],
deleted: false,
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 'LOW',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 3,
large: false,
applicationId: null,
afkTimeout: 900,
afkChannelId: 'xxxx',
systemChannelId: 'xxxx',
premiumTier: 'NONE',
premiumSubscriptionCount: 0,
explicitContentFilter: 'ALL_MEMBERS',
mfaLevel: 'NONE',
joinedTimestamp: 1633812225872,
defaultMessageNotifications: 'ONLY_MENTIONS',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: 'xxxx',
publicUpdatesChannelId: 'xxxx',
preferredLocale: 'en-US',
ownerId: 'xxxx',
emojis: [GuildEmojiManager],
stickers: [GuildStickerManager]
},
code: '22222222',
presenceCount: null,
memberCount: null,
temporary: false,
maxAge: 604800,
uses: 21,
maxUses: 0,
inviter: User {
id: 'xxxx',
bot: false,
system: false,
flags: [UserFlags],
username: 'xxxx',
discriminator: 'xxxx',
avatar: 'xxx',
banner: undefined,
accentColor: undefined
},
targetUser: null,
targetApplication: null,
targetType: null,
channel: TextChannel {
type: 'GUILD_TEXT',
deleted: false,
guild: [Guild],
guildId: 'xxxxx',
parentId: 'xxxx',
permissionOverwrites: [PermissionOverwriteManager],
messages: [MessageManager],
threads: [ThreadManager],
nsfw: false,
id: 'xxxx',
name: 'guest-chat',
rawPosition: 48,
topic: 'Guest Invitation Link',
lastMessageId: null,
rateLimitPerUser: 0
},
createdTimestamp: 1633969178889,
_expiresTimestamp: null,
stageInstance: null
}
}
console.log(newInvites) => returns below
Collection(2) [Map] {
'11111111' => Invite {
guild: Guild {
id: 'xxxx',
name: "Testing Server",
icon: null,
features: [Array],
commands: [GuildApplicationCommandManager],
members: [GuildMemberManager],
channels: [GuildChannelManager],
bans: [GuildBanManager],
roles: [RoleManager],
presences: PresenceManager {},
voiceStates: [VoiceStateManager],
stageInstances: [StageInstanceManager],
invites: [GuildInviteManager],
deleted: false,
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 'LOW',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 3,
large: false,
applicationId: null,
afkTimeout: 900,
afkChannelId: 'xxxx',
systemChannelId: 'xxxx',
premiumTier: 'NONE',
premiumSubscriptionCount: 0,
explicitContentFilter: 'ALL_MEMBERS',
mfaLevel: 'NONE',
joinedTimestamp: 1633812225872,
defaultMessageNotifications: 'ONLY_MENTIONS',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: 'xxxx',
publicUpdatesChannelId: 'xxxx',
preferredLocale: 'en-US',
ownerId: 'xxxx',
emojis: [GuildEmojiManager],
stickers: [GuildStickerManager]
},
code: '11111111',
presenceCount: null,
memberCount: null,
temporary: false,
maxAge: 604800,
uses: 40,
maxUses: 0,
inviter: User {
id: 'xxxx',
bot: false,
system: false,
flags: [UserFlags],
username: 'xxxx',
discriminator: 'xxxx',
avatar: 'xxxx',
banner: undefined,
accentColor: undefined
},
targetUser: null,
targetApplication: null,
targetType: null,
channel: TextChannel {
type: 'GUILD_TEXT',
deleted: false,
guild: [Guild],
guildId: 'xxxx',
parentId: 'xxxx',
permissionOverwrites: [PermissionOverwriteManager],
messages: [MessageManager],
threads: [ThreadManager],
nsfw: false,
id: 'xxxx',
name: 'welcome',
rawPosition: 3,
topic: null,
lastMessageId: 'xxxx',
rateLimitPerUser: 0
},
createdTimestamp: 1633922331801,
_expiresTimestamp: null,
stageInstance: null
},
'22222222' => Invite {
guild: Guild {
id: '878285237082271744',
name: "Testing Server",
icon: null,
features: [Array],
commands: [GuildApplicationCommandManager],
members: [GuildMemberManager],
channels: [GuildChannelManager],
bans: [GuildBanManager],
roles: [RoleManager],
presences: PresenceManager {},
voiceStates: [VoiceStateManager],
stageInstances: [StageInstanceManager],
invites: [GuildInviteManager],
deleted: false,
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 'LOW',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 3,
large: false,
applicationId: null,
afkTimeout: 900,
afkChannelId: 'xxxx',
systemChannelId: 'xxxx',
premiumTier: 'NONE',
premiumSubscriptionCount: 0,
explicitContentFilter: 'ALL_MEMBERS',
mfaLevel: 'NONE',
joinedTimestamp: 1633812225872,
defaultMessageNotifications: 'ONLY_MENTIONS',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: 'xxxx',
publicUpdatesChannelId: 'xxxx',
preferredLocale: 'en-US',
ownerId: 'xxxx',
emojis: [GuildEmojiManager],
stickers: [GuildStickerManager]
},
code: '22222222',
presenceCount: null,
memberCount: null,
temporary: false,
maxAge: 604800,
uses: 22,
maxUses: 0,
inviter: User {
id: 'xxxx',
bot: false,
system: false,
flags: [UserFlags],
username: 'xxxx',
discriminator: 'xxxx',
avatar: 'xxxx',
banner: undefined,
accentColor: undefined
},
targetUser: null,
targetApplication: null,
targetType: null,
channel: TextChannel {
type: 'GUILD_TEXT',
deleted: false,
guild: [Guild],
guildId: 'xxxx',
parentId: 'xxxx',
permissionOverwrites: [PermissionOverwriteManager],
messages: [MessageManager],
threads: [ThreadManager],
nsfw: false,
id: 'xxxx',
name: 'guest-chat',
rawPosition: 48,
topic: 'Guest Invitation Link',
lastMessageId: null,
rateLimitPerUser: 0
},
createdTimestamp: 1633969178889,
_expiresTimestamp: null,
stageInstance: null
}
}
console.log(usedInvite) => returns undefined
The error message I get is obviously:
TypeError: Cannot read property 'code' of undefined
The issue you are having most likely stems from the fact that you are saving the entire Invites Collection object in your guildInvites Map. Remember that in Javascript, when you save a single object in multiple different locations, each location still points to the same object. Basically, when you save the invites object or invite.guild.invites.fetch() to your guildInvites Map, it refers to the exact same object as newInvites will. In other words, cachedInvites and newInvites are both referring to the same object; because of this, they will contain the exact same values. Whenever an invite in newInvites is updated, it will automatically also update the invite in cachedInvites. This may be happening only now due to some changes in discord.js' code for invite management in v13.
I have not, however, looked at the discord.js source code for the new InviteManager, so it is possible that some other, similar issue is at play here. However, the solution in this answer works regardless.
Because the cache and new invite lists were both the same, the uses between the cached and used invite ended up being equal (causing the cachedInvites.get(inv.code).uses < inv.uses condition to not be met). Thus, newInvites.find() could not find the invite you were looking for, and usedInvite ended up being undefined.
There are several ways you could fix this issue. My preference is to not save the entire invites collection to your invite cache. Since you only need to know the cached invite's code and old number of uses, you only need to save that information. No need to save entire Invite objects to your cache when you only need two small pieces of information from each cached invite.
This is my proposed new structure of your cachedInvites. As you can see, it is much simpler and more efficient than before. It also solves the aforementioned possible JS issues with a single object being saved to multiple locations, by not directly saving the invites object in your cache.
Collection(2) [Map] {
'11111111' => 40,
'22222222' => 21
}
And here is my full solution, using this new, simpler structure for cached invites. I've tested it, and it works:
client.on('inviteCreate', async invite => {
const invites = await invite.guild.invites.fetch();
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses));
guildInvites.set(invite.guild.id, codeUses);
})
client.once('ready', () => {
client.guilds.cache.forEach(guild => {
guild.invites.fetch()
.then(invites => {
console.log("INVITES CACHED");
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses));
guildInvites.set(guild.id, codeUses);
})
.catch(err => {
console.log("OnReady Error:", err)
})
})
})
client.on('guildMemberAdd', async member => {
const cachedInvites = guildInvites.get(member.guild.id)
const newInvites = await member.guild.invites.fetch();
try {
const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code) < inv.uses);
console.log("Cached", [...cachedInvites.keys()])
console.log("New", [...newInvites.values()].map(inv => inv.code))
console.log("Used", usedInvite)
console.log(`The code ${usedInvite.code} was just used by ${member.user.username}.`)
} catch (err) {
console.log("OnGuildMemberAdd Error:", err)
}
newInvites.each(inv => cachedInvites.set(inv.code, inv.uses));
guildInvites.set(member.guild.id, cachedInvites);
});

React testing library form submit event is different from the real browser

so I am trying to test a form which is implemented in react. When I submit a form through jest, I get a different event as when I submit the event through the browser.
The test I am using is this one:
it("shows success message if registering was successful", async () => {
fetchMock.mockReturnValueOnce(Promise.resolve(new Response("", { status: 200 })));
const wrapper = render(<Provider store={getStore()}>
<RegisterComponent/>
</Provider>);
const emailTextfield = wrapper.getByPlaceholderText(/email#domain.de/i);
const password = wrapper.getByPlaceholderText(/eingeben/i);
const firstName = wrapper.getByPlaceholderText(/max/i);
const lastName = wrapper.getByPlaceholderText(/mustermann/i);
const retryPassword = wrapper.getByPlaceholderText(/wiederholen/i);
const privacyPolicy = wrapper.getByRole("checkbox");
const registerButton = wrapper.getByRole("button");
fireEvent.change(emailTextfield, { target: { value: "test#test.de" } });
fireEvent.change(password, { target: { value: "Test1234!" } });
fireEvent.change(retryPassword, { target: { value: "Test1234!" } });
fireEvent.change(firstName, { target: { value: "Lukas" } });
fireEvent.change(lastName, { target: { value: "Germerott" } });
fireEvent.change(privacyPolicy, { target: { checked: true } });
fireEvent.click(registerButton);
const successMessage = await wrapper.findByText(/erfolgreich/i);
expect(successMessage).toBeTruthy();
});
So I am mounting the component and fire events for all inputs. The event which is logged is this one:
<ref *1> HTMLFormElement {
'__reactFiber$sikt1ggzmx': <ref *2> FiberNode {
tag: 5,
key: null,
elementType: 'form',
type: 'form',
stateNode: [Circular *1],
return: FiberNode {
tag: 0,
key: null,
elementType: [Function: RegisterComponent],
type: [Function: RegisterComponent],
stateNode: null,
return: [FiberNode],
child: [Circular *2],
sibling: null,
index: 0,
ref: null,
pendingProps: {},
memoizedProps: {},
updateQueue: [Object],
memoizedState: [Object],
dependencies: [Object],
mode: 0,
flags: 0,
nextEffect: null,
firstEffect: null,
lastEffect: null,
lanes: 0,
childLanes: 0,
alternate: [FiberNode],
actualDuration: 0,
actualStartTime: -1,
selfBaseDuration: 0,
treeBaseDuration: 0,
_debugID: 10780,
_debugSource: [Object],
_debugOwner: null,
_debugNeedsRemount: false,
_debugHookTypes: [Array]
},
child: FiberNode {
tag: 11,
key: null,
elementType: [Object],
type: [Object],
stateNode: null,
return: [Circular *2],
child: [FiberNode],
sibling: null,
index: 0,
ref: null,
pendingProps: [Object],
memoizedProps: [Object],
updateQueue: [Object],
memoizedState: [Object],
dependencies: [Object],
mode: 0,
flags: 0,
nextEffect: null,
firstEffect: null,
lastEffect: null,
lanes: 0,
childLanes: 0,
alternate: [FiberNode],
actualDuration: 0,
actualStartTime: -1,
selfBaseDuration: 0,
treeBaseDuration: 0,
_debugID: 10784,
_debugSource: [Object],
_debugOwner: [FiberNode],
_debugNeedsRemount: false,
_debugHookTypes: [Array]
},
sibling: null,
index: 0,
ref: null,
pendingProps: {
onSubmit: [Function: submit],
'data-testid': 'formular',
children: [Object]
},
memoizedProps: {
onSubmit: [Function: submit],
'data-testid': 'formular',
children: [Object]
},
updateQueue: null,
memoizedState: null,
dependencies: null,
mode: 0,
flags: 0,
nextEffect: null,
firstEffect: null,
lastEffect: null,
lanes: 0,
childLanes: 0,
alternate: FiberNode {
tag: 5,
key: null,
elementType: 'form',
type: 'form',
stateNode: [Circular *1],
return: [FiberNode],
child: [FiberNode],
sibling: null,
index: 0,
ref: null,
pendingProps: [Object],
memoizedProps: [Object],
updateQueue: null,
memoizedState: null,
dependencies: null,
mode: 0,
flags: 0,
nextEffect: null,
firstEffect: [FiberNode],
lastEffect: [FiberNode],
lanes: 0,
childLanes: 1,
alternate: [Circular *2],
actualDuration: 0,
actualStartTime: -1,
selfBaseDuration: 0,
treeBaseDuration: 0,
_debugID: 10782,
_debugSource: [Object],
_debugOwner: [FiberNode],
_debugNeedsRemount: false,
_debugHookTypes: null
},
actualDuration: 0,
actualStartTime: -1,
selfBaseDuration: 0,
treeBaseDuration: 0,
_debugID: 10782,
_debugSource: {
fileName: '/Users/lukasgermerott/Dev/flundr/clientnew/src/components/Register.tsx',
lineNumber: 61,
columnNumber: 12
},
_debugOwner: FiberNode {
tag: 0,
key: null,
elementType: [Function: RegisterComponent],
type: [Function: RegisterComponent],
stateNode: null,
return: [FiberNode],
child: [Circular *2],
sibling: null,
index: 0,
ref: null,
pendingProps: {},
memoizedProps: {},
updateQueue: [Object],
memoizedState: [Object],
dependencies: [Object],
mode: 0,
flags: 0,
nextEffect: null,
firstEffect: null,
lastEffect: null,
lanes: 0,
childLanes: 0,
alternate: [FiberNode],
actualDuration: 0,
actualStartTime: -1,
selfBaseDuration: 0,
treeBaseDuration: 0,
_debugID: 10780,
_debugSource: [Object],
_debugOwner: null,
_debugNeedsRemount: false,
_debugHookTypes: [Array]
},
_debugNeedsRemount: false,
_debugHookTypes: null
},
'__reactProps$sikt1ggzmx': {
onSubmit: [Function: submit],
'data-testid': 'formular',
children: {
'$$typeof': Symbol(react.element),
type: [Object],
key: null,
ref: null,
props: [Object],
_owner: [FiberNode],
_store: {}
}
}
}
But when I log the same event in the browser I am getting this one
<form>
<div class=​"MuiGrid-root MuiGrid-container MuiGrid-spacing-xs-2 MuiGrid-direction-xs-column">
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<h5 class=​"MuiTypography-root MuiTypography-h5">​Registration​</h5>
</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<p class=​"MuiTypography-root MuiTypography-body1">​Persönliche Daten​</p>
</div>​
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
<div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
</div>​
</form>
This is right because now I can access the values through the event. My onsubmit function is the following:
function submit(event: React.SyntheticEvent) {
event.preventDefault();
// Create target object to extract information from
const target = event.target as typeof event.target & {
email: { value: string };
firstName: { value: string };
lastName: { value: string };
privacyPolicy: { checked: boolean };
};
console.log(target, "TARGET");
const user : IUserRegistrationModel = {
email: target.email.value,
firstName: target.firstName.value,
lastName: target.lastName.value,
password: password,
privacyPolicy: target.privacyPolicy.checked,
};
dispatch(authActions.register(user));
}
The Problem in the test is: When it submits the event, it cant extract the values from the event and simply crashes. With the browser event it works fine.
Do you guys have an idea?
Edit: Reproduced example https://codesandbox.io/s/brave-goldberg-8hfri?file=/src/App.tsx
It's a duplicate of this one: https://stackoverflow.com/a/61537739/1980235
The problem you have it with trying to access the input directly from event.target. You should access it from event.target.elements instead: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements.
Based on the given sandbox, I was able to get the tests passing by updating the following code:
function onSubmit(event: React.SyntheticEvent<HTMLFormElement>) {
event.preventDefault();
// Create target object to extract information from
const payload = event.currentTarget.elements as typeof event.currentTarget.elements & {
email: { value: string };
};
console.log(payload.email.value);
setShow(true);
}

How to get just the id of a channel

I have a script where a user can specify a channel to be the welcome channel and it will save the channel in quick.db but when I want to send an embed to the specified channel it won't let me. So I console.log()
and I saw that it returned everything.
TextChannel {
type: 'text',
deleted: false,
id: '730763402229841980',
name: '�┊�è�������',
rawPosition: 1,
parentID: '730762991502622752',
permissionOverwrites: Collection [Map] {},
topic: null,
nsfw: false,
lastMessageID: '739703571565641748',
rateLimitPerUser: 0,
lastPinTimestamp: null,
guild: Guild {
members: GuildMemberManager {
cacheType: [Function: Collection],
cache: [Collection [Map]],
guild: [Circular]
},
channels: GuildChannelManager {
cacheType: [Function: Collection],
cache: [Collection [Map]],
guild: [Circular]
},
roles: RoleManager {
cacheType: [Function: Collection],
cache: [Collection [Map]],
guild: [Circular]
},
presences: PresenceManager {
cacheType: [Function: Collection],
cache: [Collection [Map]]
},
voiceStates: VoiceStateManager {
cacheType: [Function: Collection],
cache: Collection [Map] {},
guild: [Circular]
},
deleted: false,
available: true,
id: '730762360272191508',
shardID: 0,
name: 'Serv sans nom',
icon: null,
splash: null,
region: 'southafrica',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: null,
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1596429038364,
defaultMessageNotifications: 'ALL',
systemChannelFlags: SystemChannelFlags { bitfield: 0 },
vanityURLCode: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
ownerID: '380421367704584193',
cacheType: [Function: Collection],
cache: Collection [Map] {},
guild: [Circular]
}
},
messages: MessageManager {
cacheType: [Function: LimitedCollection],
cache: LimitedCollection [Map] { maxSize: 200 },
channel: [Circular]
},
_typing: Map {}
}
The method I used to get the channel
Client.on('guildMemberAdd', member => {
console.log(db.get(`wl_channel`))
const welcome = db.get(`wl_YN${member.guild.id}`)
const embed = new Discord.MessageEmbed()
.setTitle(`Welcome ***${member.displayName}***`)
.setColor("#2163D7")
.addFields({ name: `**${member.displayName}**`, value: 'Please read the **rules**'},{ name: `You are our ` , value: `***${member.guild.memberCount}*** th member!`})
.setImage(member.user.avatarURL())
.setThumbnail(member.user.avatarURL())
if(welcome === true){
console.log(member.guild.channels.cache.get(db.get(`wl_channel`).id))
}
});
How I saved the channel
db.set(`wl_channel`, message.mentions.channels.first().id)
Any help is appreciated
Store the channels name in the database:
db.set(`wl_channel`, message.mentions.channels.first().name)
Then obtain the channel using the following:
Client.on('guildMemberAdd', member => {
console.log(db.get(`wl_channel`))
let welcomeChannel = db.get(`wl_channel`)
const welcome = db.get(`wl_YN${member.guild.id}`)
const embed = new Discord.MessageEmbed()
.setTitle(`Welcome ***${member.displayName}***`)
.setColor("#2163D7")
.addFields({ name: `**${member.displayName}**`, value: 'Please read the **rules**'},{ name: `You are our ` , value: `***${member.guild.memberCount}*** th member!`})
.setImage(member.user.avatarURL())
.setThumbnail(member.user.avatarURL())
if(welcome === true){
let channel = message.channels.find(channel => channel.name === welcomeChannel);
channel.send(embed);
}
});

Resources